Python 是否存在列表的协变可变版本?
我已经将我实际上想要说明的代码简化为以下最低版本:Python 是否存在列表的协变可变版本?,python,python-typing,Python,Python Typing,我已经将我实际上想要说明的代码简化为以下最低版本: def打印(数字或非): 对于i,枚举中的数字(数字或非): 如果数字为“无”: 数字_或_nones[i]=0 打印(“NOOOO”) 其他: 打印(数字) 数字=[1,2,3,4] 打印它(数字) 我想为参数numbers\u或\u nones添加注释,该参数是print\u it。它需要 。。。元素为可选[int] 。。。宜人的 。。。支持索引分配 这种情况下正确的类型是什么?请注意,无法更改number:List[int]的类型。
def打印(数字或非):
对于i,枚举中的数字(数字或非):
如果数字为“无”:
数字_或_nones[i]=0
打印(“NOOOO”)
其他:
打印(数字)
数字=[1,2,3,4]
打印它(数字)
我想为参数numbers\u或\u nones
添加注释,该参数是print\u it
。它需要
- 。。。元素为
可选[int]
- 。。。宜人的
- 。。。支持索引分配
number:List[int]
的类型。我能看到的唯一选项是使用键入.重载
列表
最简单的方法是List[Optional[int]]
。然而,这使:
error: Argument 1 to "print_it" has incompatible type "List[int]"; expected "List[Optional[int]]"
note: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
note: Consider using "Sequence" instead, which is covariant
序列
可变序列
简短回答:不存在协变可变集合,这里列出了处理这种情况的可能策略
为什么可变集合不能是协变的?
因为这会导致严重的问题,比如:
def make_first_None(数字或非数字:可变序列[可选[int]]):
数字\u或\u nones[0]=无
数字:列表[int]=[1,2,3,4]
先做无(数字)#错误!!数字不再是列表[int]!!!
关于可变集合为何必须是不变的,这里有一个更详细的解释
对于这种情况,文档中列出的三种策略如下所示:
- 使用显式类型批注:
编号:列表[可选[int]=[1,2,3,4]
打印它(数字)
- 复印一份,然后传给我
- 使用不可变集合
def print\u it(数字或非数字:顺序[可选[int]])->List[int]:
对于数字中的数字:
如果数字为“无”:
打印(“NOOOO”)
其他:
打印(数字)
返回[数字或0表示数字中的数字]
数字=[1,2,3,4]
打印它(数字)
List[Union[None,int]]
?@EhteshamSiddiqui,与List[Optional[int]]
相同(“List”部分)
Unsupported target for indexed assignment ("Sequence[Optional[int]]")
error: Argument 1 to "print_it" has incompatible type "List[int]"; expected "MutableSequence[Optional[int]]"
print_it(list(numbers))