Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/methodtools.py: 77%

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""":mod:`methodtools` --- functools for methods 

2=============================================== 

3 

4Expand functools features to methods, classmethods, staticmethods and even for 

5(unofficial) hybrid methods. 

6 

7For now, methodtools only provides :func:`methodtools.lru_cache`. 

8 

9Use methodtools module instead of functools module. Than it will work as you 

10expected - cache for each bound method. 

11 

12.. code-block:: python 

13 

14 from methodtools import lru_cache 

15 

16 class A(object): 

17 

18 # cached method. the storage lifetime follows `self` object 

19 @lru_cache() 

20 def cached_method(self, args): 

21 ... 

22 

23 # cached classmethod. the storage lifetime follows `A` class 

24 @lru_cache() # the order is important! 

25 @classmethod # always lru_cache on top of classmethod 

26 def cached_classmethod(self, args): 

27 ... 

28 

29 # cached staticmethod. the storage lifetime follows `A` class 

30 @lru_cache() # the order is important! 

31 @staticmethod # always lru_cache on top of staticmethod 

32 def cached_staticmethod(self, args): 

33 ... 

34 

35 @lru_cache() # just same as functools.lru_cache 

36 def cached_function(): 

37 ... 

38""" 

39 

40import functools 

41from wirerope import Wire, WireRope 

42 

43__version__ = '0.4.7' 

44__all__ = 'lru_cache', 

45 

46 

47if hasattr(functools, 'lru_cache'): 

48 _functools_lru_cache = functools.lru_cache 

49else: 

50 try: 

51 import functools32 

52 except ImportError: 

53 # raise AttributeError about fallback failure 

54 functools.lru_cache # install `functools32` to run on py2 

55 else: 

56 _functools_lru_cache = functools32.lru_cache 

57 

58 

59class _LruCacheWire(Wire): 

60 

61 def __init__(self, rope, *args, **kwargs): 

62 super(_LruCacheWire, self).__init__(rope, *args, **kwargs) 

63 lru_args, lru_kwargs = rope._args 

64 wrapper = _functools_lru_cache( 

65 *lru_args, **lru_kwargs)(self.__func__) 

66 self.__call__ = wrapper 

67 self.cache_clear = wrapper.cache_clear 

68 self.cache_info = wrapper.cache_info 

69 

70 def __call__(self, *args, **kwargs): 

71 # descriptor detection support - never called 

72 return self.__call__(*args, **kwargs) 

73 

74 def _on_property(self): 

75 return self.__call__() 

76 

77 

78@functools.wraps(_functools_lru_cache) 

79def lru_cache(*args, **kwargs): 

80 return WireRope(_LruCacheWire, wraps=True, rope_args=(args, kwargs))