Home > Enterprise >  How to access args of generic class
How to access args of generic class

Time:11-01

If I have a class A:

T = TypeVar("T")

class A(Generic[T]):
    a: T

How do I access the Generic[T] with the type-object A

typing.get_origin(A[...]).__bases__ just returns a <class 'typing.Generic'> instead of typing.Generic[~T]

CodePudding user response:

You are looking for __orig_bases__. That is set by the type metaclass when a new class is created. It is mentioned here in PEP 560, but is otherwise hardly documented.

This attribute contains (as the name suggests) the original bases as they were passed to the metaclass constructor in the form of a tuple. This distinguishes it from __bases__, which contains the already resolved bases as returned by types.resolve_bases.

Here is a working example:

from typing import Generic, TypeVar

T = TypeVar("T")

class A(Generic[T]):
    a: T

class B(A[int]):
    pass

print(A.__orig_bases__)  # (typing.Generic[~T],)
print(B.__orig_bases__)  # (__main__.A[int],)

Since it is poorly documented, I would be careful, where you use it. If you add more context to your question, maybe we'll find a better way to accomplish what you are after.

Possibly related or of interest:

Access type argument in any specific subclass of user-defined Generic[T] class

  • Related