Managing Default Parameters to Avoid Unintended Mutation
In Python, default parameters can sometimes lead to unexpected behavior when they are mutable objects. For instance, using an empty list as the default parameter of a function can cause the list to "remember" old data added to it in previous calls.
Consider the following function:
When called the first time, the default list is created and "a" is appended. However, subsequent calls to the function continue to update the same list, resulting in unintended behavior. To address this issue, we must ensure that a new empty list is used each time the function is called.
One approach is to explicitly set the default parameter to None and check for it within the function:
This method ensures that a new empty list is created when the function is called without an explicit argument.
Alternatively, you can use a comprehension to create the list and assign it to the default parameter:
This approach also effectively generates a new empty list on each call.
The Python documentation recommends using None as the default parameter and checking for it explicitly. Comparisons to None should be made using the "is" or "is not" operators, as per PEP 8 guidelines.
The above is the detailed content of How Can I Prevent Unexpected Behavior with Mutable Default Parameters in Python?. For more information, please follow other related articles on the PHP Chinese website!