Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python terminology: interface vs. protocol

Can someone explain the difference between the terms protocol and interface in the context of Python programming?

I'm seeing references to the term "protocol" in things like the buffer protocol and PEP 544, but want to make sure that I understand what this term means, and when and where, you'd use it differently from the general idea of an "interface".

like image 480
Dave Avatar asked Apr 30 '26 10:04

Dave


1 Answers

Before I attempt to answer this question, recall the definition of interfaces:

An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement.

Source: Microsoft Docs

Interfaces are used in statically typed languages to describe that two independent objects "implement the same behaviour". The interfaces are formally declared in code and enforced by the compiler (hence the must in the definition of interfaces above). They are one way of telling the type system that two objects can theoretically be substituted for each other (and are therefore related in a way). The other way is inheritance. If they cannot, the compiler throws an error.

Opposing to that, dynamically typed languages like Python do not require mechanisms like interfaces or inheritance to check if two objects are related. They use duck typing where the search for the appropriate function/method of an object is deduced at runtime. If found, it is executed - if not, an error is thrown. Therefore, interfaces are not required. Instead, there are so called "special methods" that can be implemented by classes to give instances certain "features", e.g. they can be hashed by implementing the __eq__ and __hash__ methods. These informal interfaces are NOT enforced by the compiler and only exist in the documentation.

To give an example for these informal interfaces, just imagine stumbling across some piece of code that implements a custom class that behaves like a list. Even though nowhere in code is this class related to any abstract sequence class, you know that it is used to produce sequence-like objects because it implements the __len__ and __getitem__ special methods.

I view protocols as much less strict version of interfaces in that they are not enforced and not all of them have to be implemented by a class. If you just want the class to be iterable, you can pick and implement the special methods that you have to implement and leave the rest of them untouched.

That being said, you can emulate interface-like behavior by using abstract base classes (ABCs).

like image 138
DocDriven Avatar answered May 02 '26 22:05

DocDriven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!