From 70c40f70d043f0b39386a8aadf3a8d6a4cb55c64 Mon Sep 17 00:00:00 2001 From: Yurii Karabas <1998uriyyo@gmail.com> Date: Mon, 2 Aug 2021 12:58:53 +0300 Subject: [PATCH] bpo-44807: Forbid to define __init__ method in Protocol classes --- Lib/test/test_typing.py | 7 +++++++ Lib/typing.py | 4 ++++ .../next/Library/2021-08-02-12-58-14.bpo-44807.UvHEKh.rst | 2 ++ 3 files changed, 13 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2021-08-02-12-58-14.bpo-44807.UvHEKh.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 6cd83a1586a136..0b811ac3e44bd3 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -1558,6 +1558,13 @@ class P(Protocol): with self.assertRaisesRegex(TypeError, "@runtime_checkable"): isinstance(1, P) + def test_protocol_init_is_forbidden(self): # see bpo-44807 + with self.assertRaisesRegex(TypeError, 'Protocols can not have __init__ method'): + class P(Protocol): + x: int + + def __init__(self, x: int): + self.x = x class GenericTests(BaseTestCase): diff --git a/Lib/typing.py b/Lib/typing.py index 16ad5ce7c2d04b..e481ce24444ac6 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -1532,6 +1532,10 @@ def _proto_hook(other): issubclass(base, Generic) and base._is_protocol): raise TypeError('Protocols can only inherit from other' ' protocols, got %r' % base) + + if '__init__' in cls.__dict__: + raise TypeError('Protocols can not have __init__ method') + cls.__init__ = _no_init diff --git a/Misc/NEWS.d/next/Library/2021-08-02-12-58-14.bpo-44807.UvHEKh.rst b/Misc/NEWS.d/next/Library/2021-08-02-12-58-14.bpo-44807.UvHEKh.rst new file mode 100644 index 00000000000000..19015dc4573822 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-08-02-12-58-14.bpo-44807.UvHEKh.rst @@ -0,0 +1,2 @@ +Forbid to define ``__init__`` method in ``Protocol`` classes. Patch provided +by Yurii Karabas.