How to access args of generic class

Question:

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]

Asked By: teaishealthy

||

Answers:

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

Answered By: Daniil Fajnberg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.