如何在Python中正确调节Union类型?

问题描述 投票:0回答:1

我写了一个python函数来处理int列表或int列表列表,即

[1,2,3]
[[1,2],[3,4]
,如下:

from typing import Sequence, Union

IntSeq = Sequence[int]

def foo(a: Union[IntSeq, Sequence[IntSeq]]):
    if isinstance(a, Sequence) and isinstance(a[0], int):
        # here type of a equals IntSeq
        b: IntSeq = a

但是,mypy 告诉我以下错误:

$ mypy bar.py
test.py:6: error: Incompatible types in assignment (expression has type "Union[Sequence[int], Sequence[Sequence[int]]]", variable has type "Sequence[int]")

如何消除这个错误?

python mypy python-typing
1个回答
0
投票

正如所讨论的,这是(并且仍然是)Mypy 的限制。

Python 现在具有用户定义的类型保护:

TypeGuard
(PEP 647) 和
TypeIs
(PEP 742)。由于 PEP 742 中指定的原因,首选
TypeIs
,但您可以选择:

游乐场链接

def is_intseq(a: object) -> TypeIs[IntSeq]:
    return isinstance(a, Sequence) and isinstance(a[0], int)
def foo(a: IntSeq | Sequence[IntSeq]) -> None:
    if is_intseq(a):
        b: IntSeq = a  # fine
© www.soinside.com 2019 - 2024. All rights reserved.