Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-123777: Allow __orig_class__ to be accessed in __init__ #123878

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5621,6 +5621,14 @@ class A:
with self.assertRaises(TypeError):
a[int]

def test_orig_class_init(self):
# See gh-123777
T = TypeVar("T")
class OrigClassInit(Generic[T]):
def __init__(self):
self.attr = self.__orig_class__
self.assertEqual(OrigClassInit[int]().attr, OrigClassInit[int])


class ClassVarTests(BaseTestCase):

Expand Down
25 changes: 24 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1290,13 +1290,36 @@ def __call__(self, *args, **kwargs):
if not self._inst:
raise TypeError(f"Type {self._name} cannot be instantiated; "
f"use {self.__origin__.__name__}() instead")
result = self.__origin__(*args, **kwargs)
clas = self.__origin__
safe_new = (clas.__new__ is object.__new__) or isinstance(clas.__new__, types.FunctionType)

if safe_new:
# GH-123777: Some types try and access __orig_class__ in their __init__
try:
result = clas.__new__(clas, *args, **kwargs)
except Exception:
# Something about the type doesn't like calling __new__
# (For example, _GenericAlias)
safe_new = False
result = clas(*args, **kwargs)
else:
# This is a C type with a custom __new__
#
# I'm worried that trying to set attributes on C types before they've been
# fully initialized will be problematic, so let's just disallow them
# from using the __orig_class__ in the initializer for now.
result = clas(*args, **kwargs)

try:
result.__orig_class__ = self
# Some objects raise TypeError (or something even more exotic)
# if you try to set attributes on them; we guard against that here
except Exception:
pass

if safe_new:
result.__init__(*args, **kwargs)

return result

def __mro_entries__(self, bases):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Allowed the ``__orig_class__`` attribute to be used in the ``__init__`` of
pure-Python types.
Loading