Mutable default parameter values in Python


Python tip:

Avoid setting mutable default parameters for functions. Instead, use None as the default and assign the mutable value inside the function.

Why?

Python evaluates a function's default parameters once, not each time the function is called. So, if you allow a mutable default parameter and mutate it, it will be mutated for all future calls.

An example👇

# wrong
def add_jan(users=[]):
    users.append("Jan")
    return users


print(add_jan())  # => ['Jan']
print(add_jan())  # => ['Jan', 'Jan']


# right
def add_jan(users=None):
    users = users or []
    users.append("Jan")
    return users


print(add_jan())  # => ['Jan']
print(add_jan())  # => ['Jan']