functools.py 965 B

123456789101112131415161718192021222324252627282930313233343536
  1. from __builtins import next
  2. class cache:
  3. def __init__(self, f):
  4. self.f = f
  5. self.cache = {}
  6. def __call__(self, *args):
  7. if args not in self.cache:
  8. self.cache[args] = self.f(*args)
  9. return self.cache[args]
  10. def reduce(function, sequence, initial=...):
  11. it = iter(sequence)
  12. if initial is ...:
  13. value = next(it)
  14. if value is StopIteration:
  15. raise TypeError("reduce() of empty iterable with no initial value")
  16. else:
  17. value = initial
  18. for element in it:
  19. value = function(value, element)
  20. return value
  21. class partial:
  22. def __init__(self, f, *args, **kwargs):
  23. self.f = f
  24. if not callable(f):
  25. raise TypeError("the first argument must be callable")
  26. self.args = args
  27. self.kwargs = kwargs
  28. def __call__(self, *args, **kwargs):
  29. kwargs.update(self.kwargs)
  30. return self.f(*self.args, *args, **kwargs)