Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

python - What is the pythonic way to avoid default parameters that are empty lists?

Sometimes it seems natural to have a default parameter which is an empty list. Yet Python produces unexpected behavior in these situations.

If for example, I have a function:

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

The first time it is called, the default will work, but calls after that will update the existing list (with one "a" each call) and print the updated version.

So, what is the Pythonic way to get the behavior I desire (a fresh list on each call)?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def my_func(working_list=None):
    if working_list is None: 
        working_list = []

    # alternative:
    # working_list = [] if working_list is None else working_list

    working_list.append("a")
    print(working_list)

The docs say you should use None as the default and explicitly test for it in the body of the function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...