Skip to content

bpo-44807: Forbid to define __init__ method in Protocol classes #27543

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

Closed
wants to merge 2 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 @@ -1610,6 +1610,14 @@ 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

def test_super_call_init(self):
class P(Protocol):
x: int
Expand Down
4 changes: 4 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,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_or_replace_init


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Forbid to define ``__init__`` method in ``Protocol`` classes. Patch provided
by Yurii Karabas.