I currently have code like this:
cache = 1
def foo():
global cache
# many
# lines
# of code
cache = 2
However, this may lead to hard-to-find-bugs in the future, because the reader may not notice that global cache
appears somewhere above cache = 2
. Alternatively, a contributor may mistakenly add def bar(): cache = 2
and forget to add the global cache
.
How can I avoid this pitfall?
Global mutables (dict, list, and set): (Read more about mutables here.) In short, mutables behave like globals without the global keyword — with the caveat they need to be wrapped in a list, set, or dict with different degrees of readability. You could even use a set.
In a scenario, where you need one central global point of access across the codebase, singletons are a good alternative for global variables. We can call a singleton as a lazily initialized global class which is useful when you have large objects — memory allocation can be deferred till when it's actually needed.
It is used to create global variables in python from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.
The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.
class Cache:
myvar = 1
def foo():
Cache.myvar = 2
This way, Cache.myvar
is practically a "global". It's possible to read/write to it from anywhere.
I prefer this over the dictionary alternative, because it allows for auto-complete of the variable names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With