为空参数设置默认值 (Python)

Setting defaults for empty arguments (Python)

假设我们有函数 f 并且我需要参数 b 默认为空列表,但由于可变默认参数的问题无法设置 b=[] .

其中哪一个是最 Pythonic 的,或者有更好的方法吗?

def f(a, b=None):
   if not b:
     b = []
   pass

def f(a, b=None):
   b = b or []
   pass

第一种形式,因为它更容易阅读。在没有任何特定上下文的情况下,您应该明确测试默认值,以避免传入值的潜在真实性问题。

def f(a, b=None):
   if b is None:
     b = []
   pass

来自PEP 8, Programming Recommendations

Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

您可以在整个 cpython 存储库中看到此方法的示例:

def f(a, b=''):
   if not b:
      b = []

   print(a)

你可以做一些简单的事情,比如"if not b"。如果您打算将默认参数设置为空字符串或将其设置为等于 None,您可以简单地使用 if 语句来定义 B 应该是什么,如果您实际上永远不会为 b 输入参数。在这个例子中,我们只是将它设置为一个空列表。