[Python-ideas] A proper way to bring real interfaces to Python

Serge Matveenko s at matveenko.ru
Sun May 5 00:05:54 EDT 2019


On Sun, May 5, 2019 at 6:42 AM Steven D'Aprano <steve at pearwood.info> wrote:
>
> On Sun, May 05, 2019 at 04:23:58AM +0300, Serge Matveenko wrote:
> > So, I would like to propose adding a third main object called
> > `interface` in addition to `object` and `type` and to use it to define
> > interface objects. Such interfaces could then be used in the class
> > definition in the following way.
>
> How will that solve the problem? Your `interface` object will still
> inherit from both object and type since everything inherits from object
> and all types inherit from type.

In my realization, `interface` stays aside from the inheritance logic.
It has its own tree of inheritance and doesn't participate in MRO of
its implementations. This is the key feature and the goal.

> > Another problem is that ABC performs checks at the moment an object is
> > being instantiated which isn't exactly the way one expects an
> > interface to work.
>
> Isn't it? That's how I expect it to work in Python, and I haven't had
> any problems with it so far.

Well, you haven't had any problems doesn't mean there are no:)

> That's not to say there aren't problems, but you should explain what
> they are rather than assume that others have experienced the same issues
> you have. Why is the late check a problem? Are you worried about
> performance?

One of the problems is that ABCs doesn't require a class to implement
anything. IF you have only class-methods and never instantiate the
class it will be never checked.

Another one is that ABCs aren't interfaces at all as they all to have
actual implementations being encapsulated in them. This causes
misunderstandings of the code and strange behaviors like in
`collection.abc` module for instance where there is a lot of
implementation and some methods are just mentioned by name. The code
could be much more clear if there were only interfaces and partial
implementation mixins.

Overall, there is no interface implementation in Python at the moment.
There is abc module indeed which is just a bunch of legacy hacks from
the times when there was no possibility to do it in a better way. Now
we have tools in the language to do it better and I think that it's
time to rethink this now.

> It isn't that I *oppose* moving the checks to class-creation time
> instead of instantiation time, but I'd like to hear more about why it is
> a problem.

The main problem that this is just checks on an instance without any
hard connection to method signatures as they defined and without any
check on type annotations or ever treating a class definition as a
proper type.


More information about the Python-ideas mailing list