Do you use the "global" statement in Python? [closed]
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
I've never had a legit use for the statement in any production code in my 3+ years of professional use of Python and over five years as a Python hobbyist. Any state I need to change resides in classes or, if there is some "global" state, it sits in some shared structure like a global cache.