Static Protocols in Python: Behaviour Over Inheritance
Briefly

Static Protocols in Python: Behaviour Over Inheritance
"Protocols have something to do with typing. With protocols, you can check whether an object is valid based on whether it has the right methods and attributes. The idea is to check for behaviour instead of inheritance. Protocols extend Python's type hints by allowing to define structural types. They can be very confusing at first and difficult to understand, especially in a real-world scenario. In my opinion, that's partly because, for the concept to click, one must mentally move away from pure object-oriented programming."
"Typing is also a gradually evolving topic in Python, with a naming scheme that has also evolved gradually and which is sometimes difficult to grasp, too. Generally, we distinguish between dynamic and static protocols. This article is about static protocols. What's mostly used - Goose Typing It's best to start with a short example. Before I knew protocols, I had used isinstance to check for a type."
Protocols enable structural typing in Python by validating objects on the presence of required methods and attributes rather than class inheritance. Static protocols provide compile-time, type-checker assurances of behavior conformity, while dynamic protocols operate at runtime. Runtime checks commonly use isinstance and ABCs, a pattern labeled here as goose typing, which ties behavior to inheritance hierarchies. Structural protocols decouple behavior from class trees and allow functions to accept any object with the correct shape. Gradual evolution of typing and naming in Python can make protocols feel advanced and counterintuitive to developers used to pure object-oriented design.
Read at Patrick Muller
Unable to calculate read time
[
|
]