Standard “duck types”
In typical Python code, many functions that can take a list or a dictas an argument only need their argument to be somehow “list-like” or“dict-like”. A specific meaning of “list-like” or “dict-like” (orsomething-else-like) is called a “duck type”, and several duck typesthat are common in idiomatic Python are standardized.
- from typing import Mapping, MutableMapping, Sequence, Iterable
- # Use Iterable for generic iterables (anything usable in "for"),
- # and Sequence where a sequence (supporting "len" and "__getitem__") is
- # required
- def f(iterable_of_ints):
- # type: (Iterable[int]) -> List[str]
- return [str(x) for x in iterator_of_ints]
- f(range(1, 3))
- # Mapping describes a dict-like object (with "__getitem__") that we won't
- # mutate, and MutableMapping one (with "__setitem__") that we might
- def f(my_dict):
- # type: (Mapping[int, str]) -> List[int]
- return list(my_dict.keys())
- f({3: 'yes', 4: 'no'})
- def f(my_mapping):
- # type: (MutableMapping[int, str]) -> Set[str]
- my_mapping[5] = 'maybe'
- return set(my_mapping.values())
- f({3: 'yes', 4: 'no'})