将两个列表连接到字典中时,
mypy
抱怨分配中的类型不兼容。像这样:
from typing import Dict
d = Dict[str, int]
ln = ['a', 'b', 'c']
lc = [3, 5, 7]
d = dict(zip(ln, lc))
print(ln)
print(lc)
print(d)
输出表明它工作正常:
% python3 blurb.py
['a', 'b', 'c']
[3, 5, 7]
{'a': 3, 'b': 5, 'c': 7}
但是
mypy
显示:
% mypy blurb.py
blurb.py:6: error: Cannot assign multiple types to name "d" without an explicit "Type[...]" annotation
blurb.py:6: error: Incompatible types in assignment (expression has type "Dict[str, int]", variable has type "Type[Dict[Any, Any]]")
Found 2 errors in 1 file (checked 1 source file)
这是为什么呢?具体来说,第二个错误看起来令人困惑。
尝试使用不同的变量名称代替
d
来表示 d = dict(zip(ln, lc))
或 d = Dict[str, int]
。
例如
from typing import Dict
d = Dict[str, int]
ln = ['a', 'b', 'c']
lc = [3, 5, 7]
x: d = dict(zip(ln, lc))
print(ln)
print(lc)
print(x)