避免空列表的默认参数的pythonic方法是什么? [英] What is the pythonic way to avoid default parameters that are empty lists?

查看:60
本文介绍了避免空列表的默认参数的pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,默认参数是一个空列表似乎很自然.然而 Python 在这些情况下会产生意外行为.

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)

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

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.

那么,获得我想要的行为的 Pythonic 方法是什么(每次调用都有一个新列表)?

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

推荐答案

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)

文档说你应该使用 None 作为默认值并明确测试在函数体中.

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

这篇关于避免空列表的默认参数的pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆