Search code examples
pythongenericspython-typing

Official API for typing.Generic.__orig_bases__


I have a generic type for which I'd like to retrieve at runtime the type of its type variable.

The following snippet runs well, but it uses Generic.__orig_bases__ which is not an official API (its use is discouraged in PEP 560 that defines it).

Is there an official API to retrieve it? And if not, is there another (officially supported) way for me to code get_t in this example?

import typing


T = typing.TypeVar("T")


class MyGeneric(typing.Generic[T]):
    @classmethod
    def get_t(cls) -> type[T]:
        for base in cls.__orig_bases__:
            if typing.get_origin(base) is MyGeneric:
                return typing.get_args(base)[0]
        raise RuntimeError("didn't work :(")


class IntImplementation(MyGeneric[int]):
    pass


assert IntImplementation.get_t() is int

Solution

  • I think with Python 3.12 we can safely say that __orig_bases__ is now documented and there's a function that can retrieve it:

    from types import get_original_bases
    print(get_original_bases(IntImplementation))
    # (__main__. MyGeneric[int],)
    

    Reference: https://docs.python.org/3/library/types.html#types.get_original_bases