Skip to content

get_original_bases does not return what cls.__orig_bases__ returns #122988

Description

@TiborVoelcker

Bug report

Bug description:

The types documentation states for the types.get_original_bases function:

For classes that have an __orig_bases__ attribute, this function returns the value of cls.__orig_bases__. For classes without the __orig_bases__ attribute, cls.__bases__ is returned.

I need the functionality of cls.__orig_bases__, but need to use types.get_original_bases to make the type checker happy.

A short MRE:

from types import get_original_bases
from typing import Generic, TypeVar

T = TypeVar("T")


class One(Generic[T]):
    pass


class Two(One[int]):
    pass


class Three(Two):
    pass


assert get_original_bases(One) == One.__orig_bases__
assert get_original_bases(Two) == Two.__orig_bases__
assert get_original_bases(Three) == Three.__orig_bases__

# Traceback (most recent call last):
#   File "c:\<cut>\test.py", line 34, in <module>
#     assert get_original_bases(Three) == Three.__orig_bases__
#            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# AssertionError

This is a easy solve, I would be happy to add a PR. Change here:

    try:
-       return cls.__dict__.get("__orig_bases__", cls.__bases__)
+       return getattr(cls, "__orig_bases__", cls.__bases__)
    except AttributeError:
        raise TypeError(
            f"Expected an instance of type, not {type(cls).__name__!r}"
        ) from None

To show this works:

from typing import Generic, TypeVar

T = TypeVar("T")


class One(Generic[T]):
    pass


class Two(One[int]):
    pass


class Three(Two):
    pass


def better_get_original_bases(cls):
    try:
        return getattr(cls, "__orig_bases__", cls.__bases__)
    except AttributeError:
        raise TypeError(
            f"Expected an instance of type, not {type(cls).__name__!r}"
        ) from None


assert better_get_original_bases(One) == One.__orig_bases__
assert better_get_original_bases(Two) == Two.__orig_bases__
assert better_get_original_bases(Three) == Three.__orig_bases__

# <No output>

CPython versions tested on:

3.12

Operating systems tested on:

Windows

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions