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
Linda HamiltonOriginal
2024-12-15 14:08:10533browse

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)

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><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><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!

Statement:
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