Debian Codegraph @

src/cachetools/keys.py

raw
1 """Key functions for memoizing decorators."""
2
3 __all__ = ("hashkey", "methodkey", "typedkey", "typedmethodkey")
4
5
6 class _HashedTuple(tuple):
7 """A tuple that ensures that hash() will be called no more than once
8 per element, since cache decorators will hash the key multiple
9 times on a cache miss. See also _HashedSeq in the standard
10 library functools implementation.
11
12 """
13
14 __hashvalue = None # default value, set in instance on first use
15
16 def __hash__(self, hash=tuple.__hash__):
17 hashvalue = self.__hashvalue
18 if hashvalue is None:
19 self.__hashvalue = hashvalue = hash(self)
20 return hashvalue
21
22 def __add__(self, other, add=tuple.__add__):
23 return _HashedTuple(add(self, other))
24
25 def __radd__(self, other, add=tuple.__add__):
26 return _HashedTuple(add(other, self))
27
28 def __getstate__(self):
29 return {}
30
31
32 # A sentinel for separating args from kwargs. Using the class itself
33 # ensures uniqueness and preserves identity when pickling/unpickling.
34 _kwmark = (_HashedTuple,)
35
36
37 def hashkey(*args, **kwargs):
38 """Return a cache key for the specified hashable arguments."""
39
40 if kwargs:
41 return _HashedTuple(args + _kwmark + tuple(sorted(kwargs.items())))
42 else:
43 return _HashedTuple(args)
44
45
46 def methodkey(self, *args, **kwargs):
47 """Return a cache key for use with cached methods."""
48 return hashkey(*args, **kwargs)
49
50
51 def typedkey(*args, **kwargs):
52 """Return a typed cache key for the specified hashable arguments."""
53
54 if kwargs:
55 sorted_kwargs = tuple(sorted(kwargs.items()))
56 key = _HashedTuple(args + _kwmark + sorted_kwargs)
57 key += tuple(type(v) for _, v in sorted_kwargs)
58 else:
59 key = _HashedTuple(args)
60 key += tuple(type(v) for v in args)
61 return key
62
63
64 def typedmethodkey(self, *args, **kwargs):
65 """Return a typed cache key for use with cached methods."""
66 return typedkey(*args, **kwargs)