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

Serge Matveenko s at matveenko.ru
Sat May 4 21:23:58 EDT 2019


Hi, all!

I believe, almost everybody is familiar with the `abc` package.

The problem is that the ABC class is not a separate thing from
`object`. So, using ABCs often results in complicated inheritance
designs and even in the infamous metaclass conflict.

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. The obvious way would be to enforce the
implementation at the moment `type` for that class is created, i.e. on
module execution time.

I'm aware there was `PEP 245 -- Python Interface Syntax` which was
rejected. However, I agree with the idea that the syntax proposed in
this PEP wasn't particularly "pythonish".

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.

```
class MyInterfaceA(interface):
    def foo():
        pass

class MyInterfaceB(interface):
    def bar():
        pass

class Implementation(implements=[MyInterfaceA, MyInterfaceB]):
    def foo():
        pass
    def bar():
        pass
```

As a proof of concept, I've implemented a library which implements the
idea and allows to use this approach right out of the box —
https://pypi.org/project/strict-interfaces/.

I would like to get any feedback for the idea and the library.

Thanks to all!


More information about the Python-ideas mailing list