oter

Protocols are informal interfaces in Python from "summary" of Fluent Python by Luciano Ramalho

Protocols are informal interfaces in Python, a term that is often used in the Python community to refer to interfaces that are not defined in code but rather are based on documentation and conventions. Essentially, a protocol is a set of methods or attributes that a class must implement in order to be considered a member of a particular category. For example, the protocol for a sequence type in Python includes methods like `__len__`, `__getitem__`, and `__contains__`. If a class implements these methods, it can be used in any context that expects a sequence, even if it does not inherit from a specific base class. One of the key benefits of protocols is that they allow for a high degree of flexibility and polymorphism in Python code. By defining interfaces in this informal way, Python encourages developers to focus on what an object can do rather than what it is. This can lead to more modular and reusable code, as objects that implement the same protocol can be used interchangeably in many contexts. In Python, protocols are often documented using docstrings and type hints, making it clear to other developers what methods and attributes are expected. This documentation can help ensure that classes that implement a protocol adhere to the expected behavior, even if they are not explicitly subclassing a common base class.
  1. Protocols are a powerful tool in Python for creating flexible and interoperable code. By focusing on interfaces rather than inheritance, developers can write code that is easier to maintain, test, and extend. By embracing protocols, Python developers can take advantage of the language's dynamic nature to create more robust and adaptable software.
  2. Open in app
    The road to your goals is in your pocket! Download the Oter App to continue reading your Microbooks from anywhere, anytime.
oter

Fluent Python

Luciano Ramalho

Open in app
Now you can listen to your microbooks on-the-go. Download the Oter App on your mobile device and continue making progress towards your goals, no matter where you are.