As regards the pro's and con's of why globals are so evil in Python, I'm going to refer you to the following page that I used myself when researching this very thing a while ago:
Why are global variables evil?
What I find interesting is that I am using a Python linter in Visual Studio Code (my IDE of choice) and this linter always highlights globals as being a problem even when implemented correctly. Between the linter errors and the advice in the link that I shared, I followed the same rule you've already mentioned. Use class variables instead of global ones in Python.
As for how to make your global variables into class variables? It's quite straightforward.
So what you have above is a module where you're declaring your my_variable
and initialising it as an empty list. So in a class, you can do the same thing as follows:
class MyClass:
def __init__(self):
self.my_variable = []
Or if you want to assign the value to the variable directly when you instantiate an instance of this class, you can also do the following:
class MyClass:
def __init__(self, my_variable):
self.my_variable = my_variable
So now you can create an instance of your MyClass
by using:
myClass = MyClass() #For the first example OR
myClass = MyClass([]) #For the second example
So now we want to change the values of the my_variable
part of MyClass
so lets do that. You can pretty much use the same function style as you're used to from your global variables for this. Just note that in order to re-assign my_variable
to a new value within the class, you'll need to use the self
keyword when referring to it, since it now belongs to a class
, as follows:
def function1(self):
self.my_variable = #Change the value of my_variable
def function2(self):
self.my_variable = #Change the value of my_variable again
So your entire class
now looks like this:
class MyClass:
def __init__(self):
self.my_variable = []
def function1(self):
self.my_variable = #Change the value of my_variable
def function2(self):
self.my_variable = #Change the value of my_variable again
So now you've converted your global
variable to a class
variable but how can we use it? First, lets assume that your class MyClass
is stored in a file called my_class.py
. Going by your Flask method example, you now do the following:
from my_class import MyClass
@app.route('/'):
myClass = MyClass()
myClass.function1()
myClass.function2()
return myClass.my_variable
And this will work exactly as you need it to!