【问题标题】:Make mypy recognize asserting type of list让 mypy 识别断言类型的列表
【发布时间】: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.numberthings 给我这个错误:

[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 认识到我在断言列表的每个元素都是特定类型?

【问题讨论】:

    标签: python types mypy


    【解决方案1】:

    您不想要“(玩家或字符串)列表”,您想要“(玩家列表)或(字符串列表)”:

    def func(things: Union[List[Player], List[str]]):
        if isinstance(things[0], Player):
            things = cast(List[Player], things)
            print(" ".join(p.number for p in things))
        else:
            things = cast(List[str], things)
            print(" ".join(things))
    

    不过,我认为没有比cast 更优雅的方式来进行类型检查了; mypy 似乎不够聪明,无法仅根据您的 things[0] 检查来推断 things 的类型,而且您无法做到 isinstance(things, List[Player])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-02-03
      • 2021-05-17
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多