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)
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)
Alternatively, you can use a one-liner:
working_list = [] if working_list is None else working_list
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!