[Python-Dev] PEP 544: Protocols (original) (raw)

Brett Cannon brett at python.org
Tue Mar 21 13:03:17 EDT 2017


On Tue, 21 Mar 2017 at 09:17 Matthias Kramm via Python-Dev < python-dev at python.org> wrote:

On Mon, Mar 20, 2017 at 2:42 PM, Ivan Levkivskyi <levkivskyi at gmail.com> wrote:

1. Backward compatibility: People are already using ABCs, including generic ABCs from typing module. If we prohibit explicit subclassing of these ABCs, then quite a lot of code will break.

Fair enough. Backwards compatibility is a valid point, and both abc.py and typing.py have classes that lend itself to becoming protocols.

Another key point is that if you block subclassing then this stops being useful to anyone not using a type checker. While the idea of protocols is to support structural typing, there is nothing wrong with having nominal typing through ABCs help enforce the structural typing of a subclass at the same time. You could argue that if you want that you define the base ABC first and then have a class that literally does nothing but inherit from that base ABC and Protocol, but that's unnecessary duplication in an API to have the structural type and nominal type separate when we have a mechanism that can support both.

The one thing that isn't clear to me is how type checkers will distinguish between 1.) Protocol methods in A that need to implemented in B so that B is considered a structural subclass of A. 2.) Extra methods you get for free when you explicitly inherit from A. To provide a more concrete example: Since Mapping implements eq, do I also have to implement eq if I want my class to be (structurally) compatible with Mapping?

If you think it makes sense to add a note that implicit subtyping is preferred (especially for user defined protocols), then this certainly could be done. Yes, I believe it would be good to mention that.

I don't think it needs to be explicitly discouraged if you want to make sure you implement the abstract methods (ABCs are useful for a reason). I do think it's fine, though, to make it very clear that whether you subclass or not makes absolutely no difference to tools validating the type soundness of the code. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20170321/f7c2082f/attachment.html>



More information about the Python-Dev mailing list