functools.py 936 B

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