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

Leave a Comment