Mypy:如何指定混合类型的列表(或序列)?

Mypy: how to specify list (or sequence) of mixed types?

这里是一些代码:

import typing

class A:
    def f(self):
        print("A")

class B:
    def f(self):
        print("B")

C = typing.Union[A,B]
Sequence_C = typing.Sequence[C]

a = A()
b = B()

d : Sequence_C = [a]+[b]

mypy 提供了这个错误:

error: List item 0 has incompatible type "B"; expected "A"

我的(可能不正确的)理解:

C = typing.Union[A,B]
Sequence_C = typing.Sequence[C]

表示Sequence_C的实例要么是A的实例序列,要么是B的实例序列。

我想创建一个类型 Sequence_C,它是 A 和 B 的实例序列。

我的动机是我需要一个实现“f”方法的实例列表。

请注意,更加明确无济于事:

import typing

class S:
    def f(self):
        raise NotImplementedError()

class A(S):
    def f(self):
        print("A")

class B(S):
    def f(self):
        print("B")

Sequence_S = typing.Sequence[S]

a = A()
b = B()

d : Sequence_S = [a]+[b]

(同样的错误)

您需要告诉类型检查器 [a][b] 将被解释为 Sequence_S,而不是 typing.Sequence[A](或 [B])明确地,例如like this:

import typing

class S:
    def f(self) -> None:
        raise NotImplementedError()

class A(S):
    def f(self) -> None:
        print("A")

class B(S):
    def f(self) -> None:
        print("B")

Sequence_S = typing.Sequence[S]

a: Sequence_S = [A()]
b: Sequence_S = [B()]

# Sequences don't support "+", see https://docs.python.org/3/glossary.html#term-sequence
d : Sequence_S = [*a, *b]