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

bpo-44807: Allow Protocol classes to define __init__ #31628

Merged
merged 7 commits into from
Apr 11, 2022
Merged
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
26 changes: 26 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,32 @@ class CG(PG[T]): pass
with self.assertRaises(TypeError):
CG[int](42)

def test_protocol_defining_init_does_not_get_overridden(self):
# check that P.__init__ doesn't get clobbered
# see https://bugs.python.org/issue44807

class P(Protocol):
x: int
def __init__(self, x: int) -> None:
self.x = x
class C: pass

c = C()
P.__init__(c, 1)
self.assertEqual(c.x, 1)

def test_concrete_class_inheriting_init_from_protocol(self):
class P(Protocol):
x: int
def __init__(self, x: int) -> None:
self.x = x

class C(P): pass

c = C(1)
self.assertIsInstance(c, C)
self.assertEqual(c.x, 1)

def test_cannot_instantiate_abstract(self):
@runtime_checkable
class P(Protocol):
Expand Down
3 changes: 2 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1741,7 +1741,8 @@ def _proto_hook(other):
issubclass(base, Generic) and base._is_protocol):
raise TypeError('Protocols can only inherit from other'
' protocols, got %r' % base)
cls.__init__ = _no_init_or_replace_init
if cls.__init__ is Protocol.__init__:
cls.__init__ = _no_init_or_replace_init


class _AnnotatedAlias(_GenericAlias, _root=True):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:class:`typing.Protocol` no longer silently replaces :meth:`__init__` methods defined on subclasses. Patch by Adrian Garcia Badaracco.