functools.py 966 B

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