OLD | NEW |
(Empty) | |
| 1 """Key functions for memoizing decorators.""" |
| 2 |
| 3 from __future__ import absolute_import |
| 4 |
| 5 __all__ = ('hashkey', 'typedkey') |
| 6 |
| 7 |
| 8 class _HashedTuple(tuple): |
| 9 |
| 10 __hashvalue = None |
| 11 |
| 12 def __hash__(self, hash=tuple.__hash__): |
| 13 hashvalue = self.__hashvalue |
| 14 if hashvalue is None: |
| 15 self.__hashvalue = hashvalue = hash(self) |
| 16 return hashvalue |
| 17 |
| 18 def __add__(self, other, add=tuple.__add__): |
| 19 return _HashedTuple(add(self, other)) |
| 20 |
| 21 def __radd__(self, other, add=tuple.__add__): |
| 22 return _HashedTuple(add(other, self)) |
| 23 |
| 24 _kwmark = (object(),) |
| 25 |
| 26 |
| 27 def hashkey(*args, **kwargs): |
| 28 """Return a cache key for the specified hashable arguments.""" |
| 29 |
| 30 if kwargs: |
| 31 return _HashedTuple(args + sum(sorted(kwargs.items()), _kwmark)) |
| 32 else: |
| 33 return _HashedTuple(args) |
| 34 |
| 35 |
| 36 def typedkey(*args, **kwargs): |
| 37 """Return a typed cache key for the specified hashable arguments.""" |
| 38 |
| 39 key = hashkey(*args, **kwargs) |
| 40 key += tuple(type(v) for v in args) |
| 41 key += tuple(type(v) for _, v in sorted(kwargs.items())) |
| 42 return key |
OLD | NEW |