Avoiding Issues with Default Parameters in Python
When working with Python's default parameters, certain complexities can arise, especially with mutable arguments. To prevent these issues, it's crucial to address the default parameter's behavior.
For instance, consider the following function:
def my_func(working_list=[]): working_list.append("a") print(working_list)
Upon the initial call, the empty list default parameter functions as expected. However, subsequent calls result in unexpected behavior where the default parameter, an empty list initially, maintains appended elements from previous executions.
To resolve this issue and create a fresh empty list with each function call, Python provides two approaches:
1. Test for None:
def my_func(working_list=None):</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">if working_list is None: working_list = [] working_list.append("a") print(working_list)
2. Conditional Assignment:
def my_func(working_list=None):</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">working_list = [] if working_list is None else working_list working_list.append("a") print(working_list)
Both solutions ensure that a new empty list is initialized before appending elements to it, thereby isolating each function call and preventing data accumulation from previous executions.
The above is the detailed content of How Can I Avoid Unexpected Behavior with Mutable Default Parameters in Python?. For more information, please follow other related articles on the PHP Chinese website!