(original) (raw)
On 20 March 2017 at 22:11, Matthias Kramm <kramm@google.com> wrote:
I am glad you like it.
On Mon, Mar 20, 2017 at 5:00 AM, Ivan Levkivskyi <levkivskyi@gmail.com> wrote:Explicitly declaring implementation-----------------------------------
To explicitly declare that a certain class implements the given protocols,Why is this necessary? The whole point of ducktyping is that you \*don't\* have to declare what you implement.I get that it looks convenient to have your protocol A also supply some of the methods you'd expect classes of type A to have. But completing an implementation in that way should be done explicitly (via including a utility class or using a decorator like functools.total\_ordering), not as side-effect of an (unnecessary) protocol declaration.
I would put the question backwards: do we need to \*prohibit\* explicit subclassing?
I think we shouldn't. Mostly for two reasons:
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.
If we prohibit explicit subclassing of these ABCs, then quite a lot of code will break.
2\. Convenience: There are existing protocol-like ABCs (that will be turned into protocols) that have many
useful "mix-in" (non-abstract) methods. For example in case of Sequence one
useful "mix-in" (non-abstract) methods. For example in case of Sequence one
only needs to implement \_\_getitem\_\_ and \_\_len\_\_ in an explicit subclass, and one gets
\_\_iter\_\_, \_\_contains\_\_, \_\_reversed\_\_, index, and count for free. Another example is Mapping,
one needs to implement only \_\_getitem\_\_, \_\_len\_\_, and \_\_iter\_\_, and one gets \_\_contains\_\_, keys,
items, values, get, \_\_eq\_\_, and \_\_ne\_\_ for free.
\_\_iter\_\_, \_\_contains\_\_, \_\_reversed\_\_, index, and count for free. Another example is Mapping,
one needs to implement only \_\_getitem\_\_, \_\_len\_\_, and \_\_iter\_\_, and one gets \_\_contains\_\_, keys,
items, values, get, \_\_eq\_\_, and \_\_ne\_\_ for free.
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.
--
Ivan