Home > Backend Development > Python Tutorial > How Can I Avoid Unexpected Behavior When Using Default Parameters in Python Functions?

How Can I Avoid Unexpected Behavior When Using Default Parameters in Python Functions?

Mary-Kate Olsen
Release: 2024-12-17 04:08:25
Original
923 people have browsed it

How Can I Avoid Unexpected Behavior When Using Default Parameters in Python Functions?

Avoiding Default Parameter Pitfalls in Python

In Python, it can be tempting to use an empty list as a default parameter. However, this can lead to unexpected behavior due to the early binding of default parameters.

Consider a function like this:

def my_func(working_list=[]):
    working_list.append("a")
    print(working_list)
Copy after login

Initially, the default parameter works as expected. However, subsequent calls continue to update the same list, resulting in a printed list that grows with each invocation.

To avoid this, explicitly test for the default parameter's existence in the function body and assign a new empty list if necessary:

def my_func(working_list=None):
    if working_list is None:
        working_list = []
    working_list.append("a")
    print(working_list)
Copy after login

Alternatively, you can use a one-liner:

working_list = [] if working_list is None else working_list
Copy after login

Aside: PEP 8 recommends using is None for comparisons with singletons like None. Avoid using == None, as it can lead to erroneous results.

The above is the detailed content of How Can I Avoid Unexpected Behavior When Using Default Parameters in Python Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template