请考虑以下事项:
from typing import TypeVar, Generic
class A(): pass
class B(A): pass
class C(A): pass
T = TypeVar("T", bound=A)
class Container(Generic[T]):
def __init__(x: T):
pass
b: Container[B] = Container(B())
c: Container[C] = Container(C())
如何输入将接受相同类型容器的任何元组列表的函数foo
:
foo([
(b, b),
(c, c)
])
但是拒绝这个(异类元组):
foo([
(c, b), # tuples elements are not the same type
(c, c)
])
我试过这个:
ListOfSameContainerTuples = list[tuple[Container[T], Container[T]]]
def foo(containers: ListOfSameContainerTuples[T]):
pass
但它不起作用:
foo([
(b, b),
(c, c)
])
# error: Argument 1 to "foo" has incompatible type "list[tuple[object, object]]";
# expected "list[tuple[Container[<nothing>], Container[<nothing>]]]" [arg-type]
foo([
(c, b),
(c, c)
])
# error: List item 0 has incompatible type "tuple[Container[C], Container[B]]"; expected "tuple[Container[C], Container[C]]" [list-item]
关于mypy的第二个错误看起来不错,但我不理解第一个:
- 为什么Mypy不知道
b
和c
的类型? - 为什么我的类型签名是
Container[<nothing>]
?
我try 了Tuple with multiple numbers of arbitrary but equal type种解决方案,但无济于事.