Rule Definition
In Python default parameter values in function and method definitions are evaluated only once during the module loading. When using a mutable object as a default parameter value (for a example, an empty list), every call to the function can potentially change the state of that object (adding new elements) that will persist in the next call. Indeed, this is a common way to keep a cache when calling functions several times.
However this can be also seen as a quirk of the language design that results in surprising behavior. This is particularly true for the less seasoned Python developers. Thus it is recommended to avoid using mutable objects as default parameter values.
Remediation
Generally one can achieve the same or eventually correct results by using `None` as default value and initializing (if needed) the corresponding parameter variable to the mutable object inside the function/method code block. If the parameter is used as a cache, depending on the context, more complex constructions might be required.
Violation Code Sample
>>> def foo(a=[]):
... a.append(5)
... print(a)
>>> foo()
[5]
>>> foo() # the result here is most likely unexpected
[5, 5]
>>> foo()
[5, 5, 5]
Fixed Code Sample
>>> def foo(a=None):
... if a is None:
... a = []
... a.append(5)
... print(a)
>>> foo()
[5]
>>> foo()
[5]
Reference
B. Slatkin, “Effective Python” (Pearson Education 2015) p. 48 (“Item 20: Use None and Docstrings to Specify Dynamic Default Arguments”)
https://docs.python.org/3/reference/compound_stmts.html#function
https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument
https://stackoverflow.com/questions/9158294/good-uses-for-mutable-function-argument-default-values
https://docs.python-guide.org/writing/gotchas/
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.