Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access args of generic class

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading