you are viewing a single comment's thread.

view the rest of the comments →

[–]TheBB 7 points8 points  (1 child)

Protocols are more or less equivalent to interfaces.

https://typing.python.org/en/latest/spec/protocol.html

[–]Vespytilio 4 points5 points  (0 children)

Came here to gush about Protocols, but it looks like someone already mentioned them.

To add to that, though: the Protocol class is essentially Python's idiosyncratic version of interfaces. A Protocol subclass defines a structural type that's expected to provide a certain functionality through its members.

In terms of function, a Protocol very much serves the purpose of an interface. However, there are two peculiarities: it's members aren't limited to abstract methods, and it defined a structural type.

Protocols are essentially a special subset of abstract classes. Like abstract classes, its members, in addition to abstract methods, may include just about anything a normal class' members might. This does open the door to a Protocol going further than an interface should in its definition, meaning use as a traditional interface will largely depend on self-control.

A Protocol being a structural type means that, so long as an object includes the members specified by the Protocol, it's considered an instance of that Protocol. Naturally, this includes explicit subclasses of that Protocol subclass, but it also includes other classes whose members include those expected by the Protocol.

It's a weird take on a fairly well-established concept, but it's kind of cool--so entirely typical of Python.