设置在Python中应该是列表的参数默认值的最佳实践? [英] Best practice for setting the default value of a parameter that's supposed to be a list in Python?

查看:243
本文介绍了设置在Python中应该是列表的参数默认值的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将列表作为参数的Python函数。如果我将参数的默认值设置为如下所示的空列表:

I have a Python function that takes a list as a parameter. If I set the parameter's default value to an empty list like this:

def func(items=[]):
    print items

Pylint会告诉我危险的默认值[]作为参数。所以我想知道这里的最佳做法是什么?

Pylint would tell me "Dangerous default value [] as argument". So I was wondering what is the best practice here?

推荐答案

不使用 作为默认值:

def func(items=None):
    if items is None:
        items = []
    print items

可变默认参数的问题是将在该函数的所有调用之间共享-请参见相关部分的重要警告 Python教程

The problem with a mutable default argument is that it will be shared between all invocations of the function -- see the "important warning" in the relevant section of the Python tutorial.

这篇关于设置在Python中应该是列表的参数默认值的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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