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

5

u/licht1nstein Jul 22 '21

Can you provide an example?

1

u/TSM- šŸ±ā€šŸ’»šŸ“š Jul 22 '21
def get_from_cache(name, cache={}):
    if name in cache: 
        return cache[name]
    cache[name] = expensive_calculation()
    return cache[name]

Though usually memoization is done with decorators because linters and IDEs will warn you about mutable defaults as they trip people up and are easy to miss at a glance.

You'd instead do something like

from functools import cache

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600

reference

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 = {}

-14

u/istira_balegina Jul 22 '21

See the docs.

7

u/licht1nstein Jul 22 '21

So none then.

0

u/istira_balegina Jul 22 '21

I did the googling for you:

Here:

https://docs.python.org/3/faq/programming.html#id13

"Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, useĀ NoneĀ as the default value and inside the function, check if the parameter isĀ NoneĀ and create a new list/dictionary/whatever if it is. For example, don’t write:

def foo(mydict={}): ...

but:

def foo(mydict=None): if mydict is None: mydict = {} # create a new dict for local namespace

This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called ā€œmemoizingā€, and can be implemented like this:

Callers can only provide two parameters and optionally pass _cache by keyword def expensive(arg1, arg2, *, _cache={}): if (arg1, arg2) in _cache: return _cache[(arg1, arg2)] # Calculate the value result = ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return result

You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste."

1

u/Efficient-Chair6250 Jul 22 '21

Calling it _cache at least makes it clear to the user. I still prefer the @cache decorator from functools