mypy:如何指定混合类型的列表(或序列)?
这里有一些代码:
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的实例是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]
相同的错误)
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:
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.
I would like to create a type Sequence_C which are sequences of instances of both A and B.
My motivation is that I need a list of instances implementing a "f" method.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要告诉类型检查器,
[a]
和[b]
应解释为sequence_s
,而不是键入。序列[a]
(或[b]
)明确,例如= strict& gist = 32daac7d4b33333333333bcde9fd5f86002ef4c0“ rel =“ nofollow noreferrer”>像这样:You need to tell the type checker that
[a]
and[b]
are to be interpreted asSequence_S
, and nottyping.Sequence[A]
(or[B]
) explicitly, e.g. like this: