我有以下代码:
from typing import Union,List,Any
v: Union[list[list[int]],list[int]] = [-1,3,1,6,-5] # Create a list of inst
if not isinstance(v[0],list):
v =[v]
v =[v] # Cast list of ints to list of list of ints
print(v)
mypy
投诉方式如下:
functions.py:5: error: Incompatible types in assignment
(expression has type "List[Union[List[List[int]], List[int]]]",
variable has type "Union[List[List[int]], List[int]]") [assignment]
Found 1 error in 1 file (checked 1 source file)
我可能不明白类型提示是如何工作的,但我真的不明白为什么以这种方式分配新的
v
变量会让mypy抱怨,因为最终对象实际上是一个list[list[int]]
。
谁能解释一下?
附言
我想补充一点:我在向 github 上不属于我的一些代码添加类型提示时遇到了这个问题,所以我无法真正触及它的“逻辑”。
显然问题是通过将
v = [v]
更改为v=[[*v]]
来解决的。
不清楚为什么...