Home > Backend Development > Python Tutorial > How Can I Avoid Unexpected Behavior with Mutable Default Parameters in Python?

How Can I Avoid Unexpected Behavior with Mutable Default Parameters in Python?

Linda Hamilton
Release: 2024-12-15 14:08:10
Original
535 people have browsed it

How Can I Avoid Unexpected Behavior with Mutable Default Parameters in Python?

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)
Copy after login

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Previous article:Why Does pytz Show Unexpected Time Zone Offsets, and How Can I Correctly Handle Them? Next article:How Can I Efficiently Create Multi-Process Pipelines in Python Using `subprocess.Popen`?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template