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

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."

1

u/Ph0X Jul 22 '21

Interesting, thanks for sharing.

Worth noting that they actually explicitly use _cache for the variable name, with the _ in front, implying that users of the function won't actually pass a value and it's technically a "private" variable for the function. In that sense, and with good documentation, I could see it. But at the same time, self-documenting code is the best kind of code, so why write confusing code you need to add comments to explain, when doing it the other way is the same amount of effort but self-documenting.

Also, that's more of a FAQ than a style guide, and I'm assuming that entry is fairly old. Most style guides would still tell you to never use that.