Union of generic types that is also generic

Viewed 360

Say I have two types (one of them generic) like this

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

And a union of A and B like this

C = A|B

Or, in pre-Python-3.10/PEP 604-syntax:

C = Union[A,B]

How do I have to change the definition of C, so that C is also generic? e.g. if an object is of type C[int], it is either

  • of type A[int] (type parameter is passed down) or
  • of type B (type parameter is ignored)
1 Answers

Rereading the mypy documentation I believe I have found my answer:

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

So, to answer my question:

C = A[T]|B

should do the trick. And it does!

Related