如何输入可变的默认参数
在 Python 中处理可变默认参数的方法是将它们设置为 None。
例如:
def foo(bar=None):
bar = [] if bar is None else bar
return sorted(bar)
如果我输入函数定义,那么唯一的类型 forbar说的bar是Optional,很明显,它不是Optional我期望sorted在其上运行该函数的时间:
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()和foo(None)和foo(bar=None)。(我认为以其他方式拥有它是没有意义的。)
编辑 #2:如果您从不键入as而只键入 as ,Mypy 将无错误地运行,尽管默认值为. 但是,强烈不建议这样做,因为此行为将来可能会发生变化,并且它还会将参数隐式键入为。(有关详细信息,请参阅此内容。)barOptionalList[int]NoneOptional