I was reading a question about the Python global statement ( "Python scope" ) and I was remembering about how often I used this statement when I was a Python beginner (I used global a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".
Do you use this statement in Python ? Has your usage of it changed with time ?
In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.
While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.
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.
To create a global variable in Python, you need to declare the variable outside the function or in a global scope.
I use 'global' in a context such as this:
_cached_result = None def myComputationallyExpensiveFunction(): global _cached_result if _cached_result: return _cached_result # ... figure out result _cached_result = result return result
I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:
def myComputationallyExpensiveFunction(): if myComputationallyExpensiveFunction.cache: return myComputationallyExpensiveFunction.cache # ... figure out result myComputationallyExpensiveFunction.cache = result return result myComputationallyExpensiveFunction.cache = None
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