Do you use the "global" statement in Python?

Aurelio Martin Massoni picture Aurelio Martin Massoni · Sep 28, 2008 · Viewed 53.3k times · Source

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 ?

Answer

Jerub picture Jerub · Sep 29, 2008

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