Do you use the "global" statement in Python? [closed]
I use 'global' in a context such as this:
_cached_result = Nonedef 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 resultmyComputationallyExpensiveFunction.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.
I've used it in situations where a function creates or sets variables which will be used globally. Here are some examples:
discretes = 0def use_discretes(): #this global statement is a message to the parser to refer #to the globally defined identifier "discretes" global discretes if using_real_hardware(): discretes = 1...
or
file1.py: def setup(): global DISP1, DISP2, DISP3 DISP1 = grab_handle('display_1') DISP2 = grab_handle('display_2') DISP3 = grab_handle('display_3') ...file2.py: import file1 file1.setup() #file1.DISP1 DOES NOT EXIST until after setup() is called. file1.DISP1.resolution = 1024, 768