r/Python • u/[deleted] • 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
r/Python • u/[deleted] • Jul 22 '21
1
u/istira_balegina Jul 22 '21
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."