什么是pythonic方法来避免默认参数是空列表?

2024-09-21 00:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

有时,有一个默认参数是空列表似乎很自然。然而Python produces unexpected behavior in these situations

例如,如果我有一个函数:

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

第一次调用它时,默认值将起作用,但之后的调用将更新现有列表(每次调用一个"a"),并打印更新的版本

那么,用什么样的方法来获得我想要的行为(每次通话都有一个新的列表)


Tags: 函数in列表参数mydeflistworking
3条回答

其他答案已经提供了所要求的直接解决方案,但是,由于这是新Python程序员的一个常见陷阱,因此有必要添加Python为何以这种方式运行的解释,这在Mutable Default Arguments下的The Hitchhikers Guide to Python中得到了很好的总结:

Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

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表示应该使用None作为默认值,并在函数体中显式使用test for it

在这种情况下,这并不重要,但您可以使用对象标识来测试无:

if working_list is None: working_list = []

您还可以利用python中如何定义布尔运算符或:

working_list = working_list or []

但是,如果调用方给您一个空列表(计为false)作为工作列表,并希望您的函数修改他给它的列表,那么这将意外地发生

相关问题 更多 >

    热门问题