-
Notifications
You must be signed in to change notification settings - Fork 258
Cannot extend built-in Protocols #561
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
Comments
Hitting the same issue -- is there a known workaround, or do I just rip out type hints from anything that requires structural subtyping until this is fixed? |
To both reporters: Exactly which versions of Python, typing (unless in the stdib), and typing_extensions did you use? |
Also, a workaround (haven't tested) is to do something like this:
(The second branch can probably also still inherit from Iterable.) |
Thanks for your responses, and all the work you do here! |
Yeah, I guess Jelle's workaround is what you need here.
|
I wanted to work on this last weekend, but didn't have time. I think the real fix would be to just allow subclassing |
Is the plan just to make exceptions for a handful of builtin Protocols like
Iterable, or will there be some indicator to say "subclassing is fine"?
|
I wanted to write that this is now solved in newly released |
If this is still a problem, it should be reported to bugs.python.org. |
Necrobump. Although this issue remains unresolved, a real-world solution finally arises. Courtesy # This is fine.
>>> from beartype.typing import Iterable, Protocol, TypeVar
>>> T = TypeVar('T')
>>> class Foo(Iterable[T], Protocol[T]): pass
# This is fine, too.
>>> import collections
>>> issubclass(Foo, collections.abc.Iterable)
True
>>> isinstance(('bar',), Foo)
True
# Actual structural subtyping or it didn't happen.
>>> class Zed(Iterable[T], Protocol[T]):
... def zeds_dead_baby(self): pass
>>> class WhosZed(tuple):
... def zeds_dead_baby(self): pass
>>> issubclass(WhosZed, Zed)
True
>>> isinstance(WhosZed("Whose motorcycle is this?"), Zed)
True
>>> isinstance(("It's a chopper, baby."), Zed)
False As the principal maintainer of @beartype,...hi! I'm as surprised as you are. 😮 |
In
typing.py
, a number of built-in protocols extend fromGeneric
, notProtocol
(egIterable
,Container
,Sized
, etc). However, at runtime theProcotol
class enforces that all bases for a class also inherit fromProtocol
. Thus the following codecauses the error
This is further confused by the fact that, in recent versions of typeshed,
typing.pyi
has these types likeIterable
extendingProtocol
and notGeneric
(opposite of runtime, but also seemingly the more "correct" version).The text was updated successfully, but these errors were encountered: