[英]How to type default list initializers in functions
I have the following function我有以下功能
def foo(main_list = None):
if main_list is None:
main_list = []
# do stuff with main_list
This is a common Python paradigm because if you have a default list, that list stays the same for all default calls.这是一个常见的 Python 范例,因为如果您有一个默认列表,那么该列表对于所有默认调用都保持不变。 So you get around that by setting it to be None
, and then resetting it the the actual default list inside the function.因此,您可以通过将其设置为None
来解决这个问题,然后将其重置为函数内的实际默认列表。
When typing this, I'd like to do:打字时,我想做:
def foo(main_list: List[int] = None):
if main_list is None:
main_list = []
# do stuff with main_list
But Mypy complains because now I'm storing None
to a List[int]
which isn't right.但是 Mypy 抱怨,因为现在我将None
存储到一个不正确的List[int]
中。
Should I...我是不是该...
Make main_list
be of type Optional[List[int]]
使main_list
的类型为Optional[List[int]]
Add in a # type: ignore
(which will also remove all the typing from the other parameters that work just fine)添加# type: ignore
(这也会从其他工作正常的参数中删除所有类型)
Some other better way of getting around this解决这个问题的其他一些更好的方法
(I really hope that the answer is #3, which is why I'm asking. Right now in my code, I have opted for option #2.) (我真的希望答案是 #3,这就是我问的原因。现在在我的代码中,我选择了选项 #2。)
Just use Optional[List[int]]
.只需使用Optional[List[int]]
。 You're not losing anything by making the parameter optional - you're explicitly handling None
within the body of the function - so there's no reason to not use the correct type.通过将参数设为可选,您不会丢失任何内容——您在函数体内显式处理None
因此没有理由不使用正确的类型。 It's Pythonic to treat empty lists and None
identically anyways.无论如何,将空列表和None
相同地对待是 Pythonic 。
The problem with # type: ignore
, as you mentioned, is that it suppresses type checking for other parameters.正如您所提到的, # type: ignore
的问题在于它禁止对其他参数进行类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.