Skip to content

Commit

Permalink
[3.9] bpo-45121: Fix RecursionError when calling Protocol.__init__ fr…
Browse files Browse the repository at this point in the history
…om a subclass' __init__ (GH-28206) (GH-28233)

Co-authored-by: Yurii Karabas <[email protected]>
  • Loading branch information
Fidget-Spinner and uriyyo authored Sep 8, 2021
1 parent d9b7d42 commit 99506dc
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1459,6 +1459,17 @@ class CustomProtocol(TestCase, Protocol):
class CustomContextManager(typing.ContextManager, Protocol):
pass

def test_super_call_init(self):
class P(Protocol):
x: int

class Foo(P):
def __init__(self):
super().__init__()

Foo() # Previously triggered RecursionError


class GenericTests(BaseTestCase):

def test_basics(self):
Expand Down
5 changes: 5 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1085,6 +1085,11 @@ def _no_init_or_replace_init(self, *args, **kwargs):
if cls._is_protocol:
raise TypeError('Protocols cannot be instantiated')

# Already using a custom `__init__`. No need to calculate correct
# `__init__` to call. This can lead to RecursionError. See bpo-45121.
if cls.__init__ is not _no_init_or_replace_init:
return

# Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
# The first instantiation of the subclass will call `_no_init_or_replace_init` which
# searches for a proper new `__init__` in the MRO. The new `__init__`
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix issue where ``Protocol.__init__`` raises ``RecursionError`` when it's
called directly or via ``super()``. Patch provided by Yurii Karabas.

0 comments on commit 99506dc

Please sign in to comment.