Closed
Description
If you're just using typing_extensions.Protocol, we backport python/cpython#31628 from Python 3.11. That means you can do this (the __init__ method on a protocol is retained, and can be used in concrete subclasses of that protocol):
>>> import typing_extensions as te
>>> class P(te.Protocol):
... x: int
... def __init__(self, x: int) -> None:
... self.x = x
...
>>> class C(P): pass
...
>>> C(1).x
1But, if you have both typing.Protocol and typing_extensions.Protocol in the mro, it doesn't work. On Python 3.8 (and, I assume, 3.9/3.10), there's this behaviour currently:
>>> import typing as t, typing_extensions as te
>>> class P(t.Protocol): pass
...
>>> class Q(P, te.Protocol):
... x: int
... def __init__(self, x: int) -> None:
... self.x = x
...
>>> class C(Q): pass
...
>>> C(1).x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'x'I've been looking at it, and I think this may not be fixable, unfortunately. Should we document that this is a known limitation?
Metadata
Metadata
Assignees
Labels
No labels
Activity
JelleZijlstra commentedon Jun 17, 2023
Thanks for finding this.
It does look hard to fix.
typing.Protocolbefore 3.11 clobbered__init__, so if you inherit from it, that's the behavior you'll get. We should simply document it, unless someone comes up with a clever way to prevent this behavior.AlexWaygood commentedon Jun 17, 2023
Another limitation: with
typing_extensions.Protocol, it is possible to create a protocol that extendstyping_extensions.Buffer:But if you have both
typing.Protocolandtyping_extensions.Protocolin the mro, it doesn't work:This is because we have
typing_extensions.Bufferin our version of_PROTO_ALLOWLIST, but it obviously doesn't exist in thetypingversion of_PROTO_ALLOWLIST:typing_extensions/src/typing_extensions.py
Lines 493 to 500 in fd1f853