Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/cachetools/keys.py: 38%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

26 statements  

1"""Key functions for memoizing decorators.""" 

2 

3__all__ = ("hashkey", "methodkey", "typedkey", "typedmethodkey") 

4 

5 

6class _HashedTuple(tuple): 

7 """A tuple subclass formerly used for cache keys. 

8 

9 Keys are now plain tuples: the key functions return their argument 

10 tuple as is, saving a copy into a subclass instance on every call. 

11 The class remains as the kwargs separator and for loading keys 

12 pickled by earlier versions, which compare equal to plain tuples. 

13 

14 """ 

15 

16 

17# A sentinel for separating args from kwargs. Using the class itself 

18# ensures uniqueness and preserves identity when pickling/unpickling. 

19_kwmark = (_HashedTuple,) 

20 

21 

22def hashkey(*args, **kwargs): 

23 """Return a cache key for the specified hashable arguments.""" 

24 

25 if kwargs: 

26 return args + _kwmark + tuple(sorted(kwargs.items())) 

27 else: 

28 return args 

29 

30 

31def methodkey(self, /, *args, **kwargs): 

32 """Return a cache key for use with cached methods.""" 

33 

34 if kwargs: 

35 return args + _kwmark + tuple(sorted(kwargs.items())) 

36 else: 

37 return args 

38 

39 

40def typedkey(*args, **kwargs): 

41 """Return a typed cache key for the specified hashable arguments.""" 

42 

43 if kwargs: 

44 sorted_kwargs = tuple(sorted(kwargs.items())) 

45 key = args + _kwmark + sorted_kwargs 

46 key += tuple([type(v) for _, v in sorted_kwargs]) 

47 else: 

48 key = args 

49 return key + tuple(map(type, args)) 

50 

51 

52def typedmethodkey(self, /, *args, **kwargs): 

53 """Return a typed cache key for use with cached methods.""" 

54 

55 if kwargs: 

56 sorted_kwargs = tuple(sorted(kwargs.items())) 

57 key = args + _kwmark + sorted_kwargs 

58 key += tuple([type(v) for _, v in sorted_kwargs]) 

59 else: 

60 key = args 

61 return key + tuple(map(type, args))