【发布时间】:2020-08-02 05:13:49
【问题描述】:
我有这样的代码
from typing import Union, List
class Player:
number: str
def func(things: List[Union[Player, str]]):
if isinstance(things[0], Player):
print(" ".join(p.number for p in things))
else:
print(" ".join(things))
Mypy 突出显示 else 块中的 p.number 和 things 给我这个错误:
[mypy error] [E] Item "str" of "Union[Player, str]" has no attribute "number"
我也试过
def func2(things: List[Union[Player, str]]):
if all(isinstance(thing, Player) for thing in things):
print(" ".join(p.number for p in things))
elif all(isinstance(thing, str) for thing in things):
print(" ".join(things))
但我得到了同样的错误。如何让 mypy 认识到我在断言列表的每个元素都是特定类型?
【问题讨论】: