1
0

functools.py 948 B

1234567891011121314151617181920212223242526272829303132333435
  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. try:
  13. value = next(it)
  14. except StopIteration:
  15. raise TypeError("reduce() of empty sequence 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)