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(likeProtocoldoes in CPython). If we're on 3.7, we don't (becausetyping.Genericwon't let us on Python 3.7).Inheriting from
typing.Genericis 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
Protocoldefines__class_getitem__on 3.7, but doesn't on 3.8, the implementations ofProtocolacross 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.pydoes this to determine whether a class isGenericorProtocol, and we go down the wrong code path iftyping.pydetermines thattyping_extensions.Protocolis a different class totyping.ProtocolTo work around that, I define
__eq__on_ProtocolMetaso thattyping.Protocol == typing_extensions.Protocolevaluates 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.Protocolisn't hashable, and loads of tests start failing.)