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, List, Set
  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(ints: Iterable[int]) -> List[str]:
  7. return [str(x) for x in ints]
  8.  
  9. f(range(1, 3))
  10.  
  11. # Mapping describes a dict-like object (with "__getitem__") that we won't
  12. # mutate, and MutableMapping one (with "__setitem__") that we might
  13. def f(my_dict: Mapping[int, str]) -> List[int]:
  14. my_mapping[5] = 'maybe' # if we try this, mypy will throw an error...
  15. return list(my_dict.keys())
  16.  
  17. f({3: 'yes', 4: 'no'})
  18.  
  19. def f(my_mapping: MutableMapping[int, str]) -> Set[str]:
  20. my_mapping[5] = 'maybe' # ...but mypy is OK with this.
  21. return set(my_mapping.values())
  22.  
  23. f({3: 'yes', 4: 'no'})