3

Suppose I have a class A that has a contains_variable method that contains multiple variables. What I want to achieve here is declaring all these variables global so that they could be used outside their current local scope.

What I don't want is to make these variables class variables or define them outside this contains_variable method since it contains self.foo and other such variables that are used in other classes and files and defining them outside the method would mean changing them everywhere else as well which would be cumbersome.

class A:

    def contains_variables(self, foo):
        self.foo = None
        var1 = 1
        var2 = 2
        var3 = 3
      # upto let's say var 28
        var 28 = 28

    def add(self):
        print('var1 + var28 = ', var1 + var28)

I realized defining other class for these variables must be a good option but then again it would mean to change every variable at every place it was used.

class globalVariables:

      foo = None
      var1 = 1
    # upto var28
      var28 = 28  

class A(globalVariables):

      print('var1 + var28 = ', globalVariables.var1 + globalVariables28)

Prepending every variable with globalVariablesjust seems unproductive.

  • You can use global keyword in this case, you can just put `global` as a prefix of your variable and it will then become a global variable. See [here](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) for more info. What you needed was a bit of googling my friend! :) – Sarques May 22 '20 at 02:55
  • See this :https://stackoverflow.com/questions/61842854/dynamically-naming-list-in-python3/61846474#61846474 – Alchimie May 22 '20 at 02:56
  • @Sarques I know I could use global, but defining global before every variable would definitely solve the issue but seems 'non-pythonic' – Shubhashish Dixit May 22 '20 at 03:00
  • @Alchimie the dictionaries are mutable so I'll have to edit the code wherever they'll be these variables will be called. – Shubhashish Dixit May 22 '20 at 03:02
  • @Shubhashish Dixit. Not exactly, dict['val1']=3 :not changed of do not... – Alchimie May 22 '20 at 03:18

1 Answers1

1

Indeed a good question and potentially valid scenario. Even I am also looking for an answer on it.

Global keyword or class.var or self.var approach is good only when 2-3 global variables.

  1. If we declare multiple variables using global keyword which we need to amend in multiple functions, then we end-up using global keyword again in each function to tell python that it is global.

  2. Passing multiple variables as args also not look clean approach.

  3. If we declare all these variables as class or instance variables to access them in multiple methods, then we end-up using self.var or class.var everywhere which pollute the entire code with self keywords.

But so far only option to declare multiple variables is to declare them as class or instance variables. Still awaiting for better solution.

RKT
  • 11
  • 2