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:

  1. from typing import Iterator, Iterable, Optional
  2.  
  3. class IntList:
  4. def __init__(self, value: int, next: Optional['IntList']) -> None:
  5. self.value = value
  6. self.next = next
  7.  
  8. def __iter__(self) -> Iterator[int]:
  9. current = self
  10. while current:
  11. yield current.value
  12. current = current.next
  13.  
  14. def print_numbered(items: Iterable[int]) -> None:
  15. for n, x in enumerate(items):
  16. print(n + 1, x)
  17.  
  18. x = IntList(3, IntList(5, None))
  19. print_numbered(x) # OK
  20. 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.

  1. def __iter__(self) -> Iterator[T]

See also Iterable.

Iterator[T]

  1. def __next__(self) -> T
  2. 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).

  1. def __len__(self) -> int

See also Sized.

Container[T]

This is a type for objects that support the in operator.

  1. def __contains__(self, x: object) -> bool

See also Container.

Collection[T]

  1. def __len__(self) -> int
  2. def __iter__(self) -> Iterator[T]
  3. 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).

  1. 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).

  1. def __abs__(self) -> T

See also SupportsAbs.

SupportsBytes

This is a type for objects that support bytes(x).

  1. def __bytes__(self) -> bytes

See also SupportsBytes.

SupportsComplex

This is a type for objects that support complex(x). Note that no arithmetic operationsare supported.

  1. def __complex__(self) -> complex

See also SupportsComplex.

SupportsFloat

This is a type for objects that support float(x). Note that no arithmetic operationsare supported.

  1. def __float__(self) -> float

See also SupportsFloat.

SupportsInt

This is a type for objects that support int(x). Note that no arithmetic operationsare supported.

  1. def __int__(self) -> int

See also SupportsInt.

SupportsRound[T]

This is a type for objects that support round(x).

  1. 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]

  1. def __await__(self) -> Generator[Any, None, T]

See also Awaitable.

AsyncIterable[T]

  1. def __aiter__(self) -> AsyncIterator[T]

See also AsyncIterable.

AsyncIterator[T]

  1. def __anext__(self) -> Awaitable[T]
  2. 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]

  1. def __enter__(self) -> T
  2. def __exit__(self,
  3. exc_type: Optional[Type[BaseException]],
  4. exc_value: Optional[BaseException],
  5. traceback: Optional[TracebackType]) -> Optional[bool]

See also ContextManager.

AsyncContextManager[T]

  1. def __aenter__(self) -> Awaitable[T]
  2. def __aexit__(self,
  3. exc_type: Optional[Type[BaseException]],
  4. exc_value: Optional[BaseException],
  5. traceback: Optional[TracebackType]) -> Awaitable[Optional[bool]]

See also AsyncContextManager.