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.

  1. from typing import Mapping, MutableMapping, Sequence, Iterable
  2.  
  3. # Use Iterable for generic iterables (anything usable in "for"),
  4. # and Sequence where a sequence (supporting "len" and "__getitem__") is
  5. # required
  6. def f(iterable_of_ints):
  7. # type: (Iterable[int]) -> List[str]
  8. return [str(x) for x in iterator_of_ints]
  9.  
  10. f(range(1, 3))
  11.  
  12. # Mapping describes a dict-like object (with "__getitem__") that we won't
  13. # mutate, and MutableMapping one (with "__setitem__") that we might
  14. def f(my_dict):
  15. # type: (Mapping[int, str]) -> List[int]
  16. return list(my_dict.keys())
  17.  
  18. f({3: 'yes', 4: 'no'})
  19.  
  20. def f(my_mapping):
  21. # type: (MutableMapping[int, str]) -> Set[str]
  22. my_mapping[5] = 'maybe'
  23. return set(my_mapping.values())
  24.  
  25. f({3: 'yes', 4: 'no'})