In Python, a protocol is a group of operations or methods that a type must support if it is to implement that protocol. Protocols needn't be defined in the source code as separate interfaces or base classes as they would in a nominally typed language such as C# or Java. It's sufficient to simply have an object provide functioning implementations of those operations.
We can organize the different collections we have encountered in Python according to which protocols they support:
Protocol | Implementing collections |
---|---|
Container |
|
Sized |
|
Iterable |
|
Sequence |
|
Mutable Sequence |
|
Mutable Set |
|
Mutable Mapping |
|
Support for a protocol demands specific behavior from a type.
The container protocol requires that membership testing using the in and not in operators be supported:
item in container item not in container