我写了一个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]")
如何消除这个错误?
正如所讨论的,这是(并且仍然是)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