Predefined protocols
The typing
module defines various protocol classes that correspondto common Python protocols, such as Iterable[T]
. If a classdefines a suitable iter
method, mypy understands that itimplements the iterable protocol and is compatible with Iterable[T]
.For example, IntList
below is iterable, over int
values:
- from typing import Iterator, Iterable, Optional
- class IntList:
- def __init__(self, value: int, next: Optional['IntList']) -> None:
- self.value = value
- self.next = next
- def __iter__(self) -> Iterator[int]:
- current = self
- while current:
- yield current.value
- current = current.next
- def print_numbered(items: Iterable[int]) -> None:
- for n, x in enumerate(items):
- print(n + 1, x)
- x = IntList(3, IntList(5, None))
- print_numbered(x) # OK
- print_numbered([4, 5]) # Also OK
The subsections below introduce all built-in protocols defined intyping
and the signatures of the corresponding methods you need to defineto implement each protocol (the signatures can be left out, as always, but mypywon’t type check unannotated methods).
Iteration protocols
The iteration protocols are useful in many contexts. For example, they allowiteration of objects in for loops.
Iterable[T]
The example above has a simple implementation of aniter
method.
- def __iter__(self) -> Iterator[T]
See also Iterable
.
Iterator[T]
- def __next__(self) -> T
- def __iter__(self) -> Iterator[T]
See also Iterator
.
Collection protocols
Many of these are implemented by built-in container types such aslist
and dict
, and these are also useful for user-definedcollection objects.
Sized
This is a type for objects that support len(x)
.
- def __len__(self) -> int
See also Sized
.
Container[T]
This is a type for objects that support the in
operator.
- def __contains__(self, x: object) -> bool
See also Container
.
Collection[T]
- def __len__(self) -> int
- def __iter__(self) -> Iterator[T]
- def __contains__(self, x: object) -> bool
See also Collection
.
One-off protocols
These protocols are typically only useful with a single standardlibrary function or class.
Reversible[T]
This is a type for objects that support reversed(x)
.
- def __reversed__(self) -> Iterator[T]
See also Reversible
.
SupportsAbs[T]
This is a type for objects that support abs(x)
. T
is the type ofvalue returned by abs(x)
.
- def __abs__(self) -> T
See also SupportsAbs
.
SupportsBytes
This is a type for objects that support bytes(x)
.
- def __bytes__(self) -> bytes
See also SupportsBytes
.
SupportsComplex
This is a type for objects that support complex(x)
. Note that no arithmetic operationsare supported.
- def __complex__(self) -> complex
See also SupportsComplex
.
SupportsFloat
This is a type for objects that support float(x)
. Note that no arithmetic operationsare supported.
- def __float__(self) -> float
See also SupportsFloat
.
SupportsInt
This is a type for objects that support int(x)
. Note that no arithmetic operationsare supported.
- def __int__(self) -> int
See also SupportsInt
.
SupportsRound[T]
This is a type for objects that support round(x)
.
- def __round__(self) -> T
See also SupportsRound
.
Async protocols
These protocols can be useful in async code. See Typing async/awaitfor more information.
Awaitable[T]
- def __await__(self) -> Generator[Any, None, T]
See also Awaitable
.
AsyncIterable[T]
- def __aiter__(self) -> AsyncIterator[T]
See also AsyncIterable
.
AsyncIterator[T]
- def __anext__(self) -> Awaitable[T]
- def __aiter__(self) -> AsyncIterator[T]
See also AsyncIterator
.
Context manager protocols
There are two protocols for context managers – one for regular contextmanagers and one for async ones. These allow defining objects that canbe used in with
and async with
statements.
ContextManager[T]
- def __enter__(self) -> T
- def __exit__(self,
- exc_type: Optional[Type[BaseException]],
- exc_value: Optional[BaseException],
- traceback: Optional[TracebackType]) -> Optional[bool]
See also ContextManager
.
AsyncContextManager[T]
- def __aenter__(self) -> Awaitable[T]
- def __aexit__(self,
- exc_type: Optional[Type[BaseException]],
- exc_value: Optional[BaseException],
- traceback: Optional[TracebackType]) -> Awaitable[Optional[bool]]
See also AsyncContextManager
.