How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default arguments "remembering" old data)?
default-parameters, python
Solution
def my_func(working_list=None):
if working_list is None:
working_list = []
# alternative:
# working_list = [] if working_list is None else working_list
working_list.append("a")
print(working_list)
The docs say you should use `None` as the default and explicitly test for it in the body of the function.
Problem
Sometimes it seems natural to have a default parameter which is an empty list. However, Python produces unexpected behavior in these situations. For example, consider this function: ``` def my_func(working_list=[]): working_list.append("a") print(working_list) ``` The first time it is called, the default will work, but calls after that will update the existing list (with one `"a"` each call) and print the updated version. How can I fix the function so that, if it is called repeatedly without an explicit argument, a new empty list is used each time?
Related problems
- What is the difference between "is None" and "== None"
- How can I use an attribute of the instance as a default argument for a method?
- Good uses for mutable function argument default values?
- "Least Astonishment" and the Mutable Default Argument
- How can I bind arguments to a function in Python?
- What is memoization and how can I use it in Python?
- Why does using `arg=None` fix Python's mutable default argument issue?