处理Python中可变默认参数的方法是将它们设置为None。
例如:
def foo(bar=None):
bar = [] if bar is None else bar
return sorted(bar)
如果我输入函数定义,那么bar
的唯一类型是Optional
,但很明显,当我期望在其上运行sorted
函数时,它并不是Optional
:
def foo(bar: Optional[List[int]]=None):
bar = [] if bar is None else bar
return sorted(bar) # bar cannot be `None` here
那么我应该投掷吗?
def foo(bar: Optional[List[int]]=None):
bar = [] if bar is None else bar
bar = cast(List[int], bar) # make it explicit that `bar` cannot be `None`
return sorted(bar)
我应该只是希望阅读此函数的人能看到处理默认可变参数的标准模式,并理解在函数的其余部分中,该参数不应为
Optional
吗?最好的处理方式是什么?
编辑:为了澄清,这个函数的用户应该能够以
foo()
、foo(None)
和foo(bar=None)
的方式调用foo
。(我认为没有其他更好的方式。)编辑#2:如果您从未将
bar
类型化为Optional
,而只将其作为List[int]
类型,则Mypy将无错误运行,尽管默认值为None
。然而,这是极其不推荐的,因为这种行为可能会在将来发生变化,而且它还会隐含地将参数类型定为Optional
。(有关详细信息,请参见此处。)
=None
似乎是一个更好的选择。 - user2357112[]
作为生成文档中的默认值会让人觉得可变默认值完全没有问题。 - user2357112