You can set the default value of the argument in the function definition
def foo(bar=[]):
bar.append('baz')
return bar
Running foo ()
returns the list ['baz']
>>> foo()
['baz']
Now what if we run the same code again?
>>> foo()
['baz', 'baz']
The result has changed. The reason for this is that Python only evaluates the default value of a function the first time. And the Python list is a mutable object, and ʻappend ()` adds destructive arguments to the list, resulting in unexpected results on the second run. ..
To clear this problem, make immutable objects the default. In the case of the foo
function this time
def foo(bar=None):
if bar is None:
bar = []
bar.append('baz')
return bar
To do. No matter how many times this function is called with no arguments, None is immutable, so it returns the same result every time.
>>> foo()
['baz']
>>> foo()
['baz']
In Python, str is immutable, so it's okay to use a string as the default value.