r/Python • • Jul 22 '21

Resource Do not use mutable objects as default arguments in Python

https://medium.com/geekculture/do-not-use-objects-as-default-arguments-in-python-1c940212db2e
1.3k Upvotes

218 comments sorted by

View all comments

Show parent comments

2

u/earthboundkid Jul 22 '21

This also works and doesn't use a mutable arg:

def get_from_cache(name):
    if name in get_from_cache.cache: 
        return get_from_cache.cache[name]
    get_from_cache.cache[name] = expensive_calculation()
    return get_from_cache.cache[name]

get_from_cache.cache = {}