"Least Astonishment" and the Mutable Default Argument
Python's mutable default argument behavior has long puzzled beginners and experienced developers alike. A function like foo(a=[]) unexpectedly accumulates values in a across multiple calls, leaving many questioning its rationale.
To understand the root of this seemingly flawed design, we must delve into the nature of Python functions as first-class objects. When a function is defined, it is essentially being evaluated as an object itself. This means that default parameters, like a=[] in our example, become attributes of the function object.
Hence, when a function is called, it is not the default parameter value that is evaluated, but rather the attribute that points to the list object that was created at function definition. As a result, any modifications made to the list within the function affect the shared reference, explaining the accumulating behavior of a.
This approach aligns with Python's "least astonishment" philosophy, which prioritizes consistency and adherence to object-oriented principles. Just as instance variables in classes can change over time, so can this "member data" in function objects.
This behavior also serves a practical purpose: it allows functions to have a state that persists across calls. Consider the following example:
def a(): print("a executed") return [] def b(x=a()): x.append(5) print(x) a executed >>> b() [5] >>> b() [5, 5]
Here, the value returned by a() is shared by all calls to b(), allowing the list to be modified and retained over multiple iterations. Binding the default argument at function execution would effectively create a new list each time b() is called, rendering this behavior impossible.
In conclusion, while Python's mutable default argument behavior may seem counterintuitive at first, it stems from the language's first-class function nature and aligns with principles of object-oriented programming and consistency.
The above is the detailed content of Why Does Python's Mutable Default Argument Behavior Lead to Unexpected Accumulation?. For more information, please follow other related articles on the PHP Chinese website!