]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-45121: Fix RecursionError when calling Protocol.__init__ from a subclass' __init_...
authorYurii Karabas <1998uriyyo@gmail.com>
Wed, 8 Sep 2021 10:25:09 +0000 (13:25 +0300)
committerGitHub <noreply@github.com>
Wed, 8 Sep 2021 10:25:09 +0000 (18:25 +0800)
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Core and Builtins/2021-09-07-17-10-16.bpo-45121.iG-Hsf.rst [new file with mode: 0644]

index 847d583cdafb9a8812c0d384542643617104db10..fa49b90886c30200f65b844044350553a61253c8 100644 (file)
@@ -1610,6 +1610,16 @@ class ProtocolTests(BaseTestCase):
         with self.assertRaisesRegex(TypeError, "@runtime_checkable"):
             isinstance(1, P)
 
+    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):
 
index 892f1b3506851d55e3960d648c191dcab8959dc2..e29d699283dfec9ab839ad1d0adcf6bcbd5e1d70 100644 (file)
@@ -1406,6 +1406,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__`
diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-09-07-17-10-16.bpo-45121.iG-Hsf.rst b/Misc/NEWS.d/next/Core and Builtins/2021-09-07-17-10-16.bpo-45121.iG-Hsf.rst
new file mode 100644 (file)
index 0000000..19eb331
--- /dev/null
@@ -0,0 +1,2 @@
+Fix issue where ``Protocol.__init__`` raises ``RecursionError`` when it's
+called directly or via ``super()``. Patch provided by Yurii Karabas.