[Python-Dev] PEP 544: Protocols

Ivan Levkivskyi levkivskyi at gmail.com
Tue Mar 21 12:36:45 EDT 2017


On 21 March 2017 at 17:09, Matthias Kramm <kramm at google.com> wrote:

>
> 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?
>

An implicit subtype should implement all methods, so that yes, in this case
__eq__ should be implemented for Mapping.

There was an idea to make some methods "non-protocol" (i.e. not necessary
to implement), but it was rejected,
since this complicates things. Briefly, consider this function:

def fun(m: Mapping):
    m.keys()

The question is should this be an error? I think most people would expect
this to be valid.
The same applies to most other methods in Mapping, people expect that
they are provided my Mapping. Therefore, to be on the safe side, we need
to require these methods to be implemented. If you look at definitions in
collections.abc,
there are very few methods that could be considered "non-protocol".
Therefore, it was decided
to not introduce "non-protocol" methods.

There is only one downside for this: it will require some boilerplate for
implicit subtypes of Mapping etc.
But, this applies to few "built-in" protocols (like Mapping and Sequence)
and people already subclass them.
Also, such style will be discouraged for user defined protocols. It will be
recommended to create compact
protocols and combine them. (This was discussed, but it looks like we
forgot to add an explicit statement about this.)

I will add a section on non-protocol methods to rejected/postponed ideas.

--
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20170321/e16a0401/attachment.html>


More information about the Python-Dev mailing list