fork download
  1. from functools import lru_cache
  2.  
  3. def hashifying_lru_cache(
  4. func_or_None=None, maxsize=128, typed=False, hasher=id):
  5. def decorator(func):
  6. class Hashified:
  7. def __init__(self, obj):
  8. self.obj = obj
  9. def __eq__(self, other):
  10. return hasher(self.obj) == hasher(other.obj)
  11. def __hash__(self):
  12. return hasher(self.obj)
  13. def unwrapper(*args, **kwargs):
  14. return func(
  15. *(arg.obj if isinstance(arg, Hashified) else arg
  16. for arg in args),
  17. **{name: value.obj if isinstance(value, Hashified) else value
  18. for name, value in kwargs.items()}
  19. )
  20. def wrapper(*args, **kwargs):
  21. return decorated(
  22. *(Hashified(arg) if arg.__hash__ is None else arg
  23. for arg in args),
  24. **{name: Hashified(value) if value.__hash__ is None else value
  25. for name, value in kwargs.items()}
  26. )
  27. decorated = lru_cache(maxsize=maxsize, typed=typed)(unwrapper)
  28. return wrapper
  29. return decorator if func_or_None is None else decorator(func_or_None)
  30.  
  31. @hashifying_lru_cache
  32. def sum_list(const_list):
  33. print('got', const_list)
  34. return sum(const_list)
  35.  
  36. lst = [1, 2, 3]
  37. print(sum_list(lst))
  38. print(sum_list(lst))
Success #stdin #stdout 0.07s 14024KB
stdin
Standard input is empty
stdout
got [1, 2, 3]
6
6