Stack Overflow has a lot of questions regarding global variables in python, and it seems to generate some amount of confusion for people coming from other languages. Scoping rules don’t exactly work the way a lot of people from other backgrounds expect them to.
At the same time, code is meant to be organized not so much on class level, but on module level. So when everything is not necessarily contained in classes, state that would otherwise be found in member variables can go in module-level variables.
So my question is 2 part:
1) Should I be avoiding the use of globals (specifically setting them from within functions and using the global keyword)?
2) If #1 is yes, are there common patterns where they are expected to be used?
I work in a place where lots of different languages abound and I want to mitigate confusion and make sure that pythonistas won’t hate me later.
Thank you for any constructive input.
I highly recommend you read this blog post titled Singletons and their Problems in Python. It has caused me to rethink my use of global variables. Some choice quotes:
And here is one example of problems having such shared state might cause:
That’s a common enough pattern, and I’ve done it myself… but for example a better way to do it would be:
initreturns an instance of a class that implements all the methods, and other parts of the code caninitto get a different instance with different parameters that don’t interfere with the former. The "downside" is that you have to pass this instance to any code that doesn’t want to initialize a new one, but the upside of that "downside" is that it makes it obvious what your dependencies are.Anyway, in short, I’d try to avoid it as much as possible, but if you’re ok with code having an implicit singleton then go for it.