Search code examples
pythongenericsfactorytyping

Reflect on TypeVar in Custom Generic Class method


Consider the code bellow.

>>> class A(typing.Generic[T]):
...     @classmethod
...     def foo(cls) -> None:
...         print(typing.get_args(cls))
...
>>> A[int].foo()
()
>>> typing.get_args(A[int])
(<class 'int'>,)

Is it possible to infer the concrete type stored in T in the A.foo() class method?

This is a rather generic (sic) example. A real-world use case would be to implement a generic constructor which calls T type's constructors or generic factory.


Solution

  • There is an open issue on typing repo for this particular case.