【发布时间】:2021-08-22 02:41:46
【问题描述】:
在 Python 中处理可变默认参数的方法是 set them to None。
例如:
def foo(bar=None):
bar = [] if bar is None else bar
return sorted(bar)
如果我输入函数定义,那么 bar 的唯一类型是 bar,而当我希望运行 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()和foo(None)和foo(bar=None)。 (我认为任何其他方式都没有意义。)
编辑#2:
如果您从不将bar 输入为Optional 而是仅将其输入为List[int],Mypy 将run with no errors,尽管默认值为None。但是,强烈不建议这样做,因为这种行为将来可能会改变,而且它还隐式将参数键入为Optional。 (详见this。)
【问题讨论】:
标签: python mutable typing default-arguments