Protocols in Python

Introduction

A set of operations that a type must support in order to create a protocol

It should not be defined as an interface or base class

The types must provide a working implementation

Protocol Collections in which it is applied
Container str, list, dict, range, tuple, set, bytes
Sized str, list, dict, range, tuple, set, bytes
Iterable str, list, dict, range, tuple, set, bytes
Sequence str, list, dict, tuple, bytes
Mutable Sequence list
Mutable Set set
Mutable Mapping dict

The container must support in and not in

item in container item not in container

Sized must support len()

len(container)

Iteration must be able to yield its elements one at a time on demand.

For example, they can be iterated over using a for

for item in iterable: print(item)

Sequence must support accessing an element by its index, finding the index of an element, counting the number of elements and building a reverse sequence. Also, all objects that support the Sequence protocol must support Iterable, Sized and Container.

item = sequence[index] i = sequence.index(item) num = sequence.count(item) r = reversed(sequence)

Article author: Andrei Olegovich