Don't clobber user-defined __init__
methods on protocol classes, even when typing.Protocol
is in the mro
#247
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.
Rather than trying to stop
typing.Protocol.__init_subclass__
from replacing the__init__
method on a user-defined protocol, we let it go ahead with that. We just swap it back aftertyping.Protocol.__init_subclass__
has done so, to what the__init__
method was before.The "fun" thing here is that we have to be able to figure out what the class's
__init__
method is going to be before the class has actually been created. That requires knowing what the class's mro will be before it's been created. I used Steven D'Aprano's recipe here to accomplish this: https://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/.This PR fixes the first problem I mentioned in #245. (I think we should still keep the docs note I added in #246, though -- the second problem I mentioned in #246 still exists, and in general it feels kind of unpredictable what kinds of issues might arise from mixing the two
Protocol
implementations.)In general, while it was fun to write this PR, I'm not sure the extra complexity is actually worth it here, since this is something of an edge-case bug. (Adding this much complexity to the protocol-class creation process could definitely just lead to more bugs!)
Feedback is very much welcome. I think I definitely don't have enough tests right now.