Have Protocol
inherit from typing.Generic
on 3.8+
#184
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #181.
The diff GitHub is displaying for this PR is a mess to read, but it's actually a fairly simple change. We branch on whether
sys.version_info >= (3, 8)
or not. If we're on 3.8+, we inherit fromtyping.Generic
(likeProtocol
does in CPython). If we're on 3.7, we don't (becausetyping.Generic
won't let us on Python 3.7).Inheriting from
typing.Generic
is very useful for us, because it means that we no longer have to worry about keepingtyping_extensions.Protocol.__class_getitem__
in sync with the logic intyping.Generic.__class_getitem__
. The root cause of #181 was that the two methods got out of sync; changes that were made totyping.Generic.__class_getitem__
were never backported totyping_extensions.Protocol.__class_getitem__
.Other than the fact that
Protocol
defines__class_getitem__
on 3.7, but doesn't on 3.8, the implementations ofProtocol
across the two branches are broadly the same (and broadly the same as they were before this PR).The one complication is that I had to work around this line in CPython here: https://github.com/python/cpython/blob/08b4eb83aadcbdb389b5970b51cac9be95146c2a/Lib/typing.py#L1024.
typing.py
does this to determine whether a class isGeneric
orProtocol
, and we go down the wrong code path iftyping.py
determines thattyping_extensions.Protocol
is a different class totyping.Protocol
To work around that, I define
__eq__
on_ProtocolMeta
so thattyping.Protocol == typing_extensions.Protocol
evaluates toTrue
. This is a ghastly hack, but, well, it works. (As a result of defining__eq__
, I end up also having to define__hash__
, or Python starts complaining thattyping_extensions.Protocol
isn't hashable, and loads of tests start failing.)