functools.py 961 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. Python polyfills for functools
  3. """
  4. import functools
  5. from collections.abc import Callable, Iterable
  6. from typing import TypeVar
  7. from ..decorators import substitute_in_graph
  8. __all__ = ["reduce"]
  9. _T = TypeVar("_T")
  10. _U = TypeVar("_U")
  11. _initial_missing = object()
  12. # Reference: https://docs.python.org/3/library/functools.html#functools.reduce
  13. @substitute_in_graph(functools.reduce)
  14. def reduce(
  15. function: Callable[[_U, _T], _U],
  16. iterable: Iterable[_T],
  17. initial: _U = _initial_missing, # type: ignore[assignment]
  18. /,
  19. ) -> _U:
  20. it = iter(iterable)
  21. value: _U
  22. if initial is _initial_missing:
  23. try:
  24. value = next(it) # type: ignore[assignment]
  25. except StopIteration:
  26. raise TypeError(
  27. "reduce() of empty iterable with no initial value",
  28. ) from None
  29. else:
  30. value = initial
  31. for element in it:
  32. value = function(value, element)
  33. return value