protocol
A protocol in Python defines a set of methods and attributes that a class must implement to support specific behavior or functionality.
Unlike formal interfaces, Python protocols are implicit—classes don’t need to explicitly declare which protocols they implement. Instead, a class is considered to implement a protocol if it provides all the required methods and attributes, following the principle of duck typing.
Python Protocol Examples
- Iterator Protocol: Requires
__iter__()
and__next__()
methods for iteration - Buffer Protocol: Allows objects to expose their internal memory buffers for direct access (e.g.,
bytes
,bytearray
,array.array
) - Context Manager Protocol: Requires
__enter__()
and__exit__()
methods for use withwith
statements - Sequence Protocol: Requires methods like
__len__()
and__getitem__()
for sequence-like behavior
For example, this class implements the buffer protocol. It can be used anywhere that expects a buffer-like object:
class CustomBuffer:
def __init__(self, data):
self._buffer = bytearray(data)
def __buffer__(self):
return memoryview(self._buffer)
Related Resources
Tutorial
Python Protocols: Leveraging Structural Subtyping
In this tutorial, you'll learn about Python's protocols and how they can help you get the most out of using Python's type hint system and static type checkers.
For additional information on related topics, take a look at the following resources:
By Dan Bader • Updated Jan. 17, 2025