通用类型的联合也是通用的

Union of generic types that is also generic

假设我有两种类型(其中一种是通用的),如下所示

from typing import Generic, TypeVar
T = TypeVar('T')
class A(Generic[T]): pass
class B: pass

像这样的 A 和 B 的并集

C = A|B

或者,在 Python-3.10/PEP 604 之前的语法中:

C = Union[A,B]

我如何更改 C 的定义,使 C 也是通用的?例如如果对象是 C[int] 类型,则它是

重读 mypy documentation 我相信我找到了答案:

Type aliases can be generic. In this case they can be used in two ways: Subscripted aliases are equivalent to original types with substituted type variables, so the number of type arguments must match the number of free type variables in the generic type alias. Unsubscripted aliases are treated as original types with free variables replaced with Any

所以,回答我的问题:

C = A[T]|B

应该可以解决问题。确实如此!