简体   繁体   English

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

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

Here some code:这里有一些代码:

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 provides this error: mypy 提供此错误:

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

My (possibly incorrect) undestanding:我的(可能不正确的)不理解:

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

means that instances of Sequence_C are either sequences of instances of A or sequences of instances of B.表示 Sequence_C 的实例要么是 A 的实例序列,要么是 B 的实例序列。

I would like to create a type Sequence_C which are sequences of instances of both A and B.我想创建一个类型 Sequence_C,它是 A 和 B 的实例序列。

My motivation is that I need a list of instances implementing a "f" method.我的动机是我需要一个实现“f”方法的实例列表。

Note that being more explicit did not help:请注意,更明确并没有帮助:

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]

(same error) (同样的错误)

You need to tell the type checker that [a] and [b] are to be interpreted as Sequence_S , and not typing.Sequence[A] (or [B] ) explicitly, eg like this :您需要告诉类型检查器[a][b]将被解释为Sequence_S ,而不是显式typing.Sequence[A] (或[B] ), 例如

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM