@@ -36,6 +36,8 @@ def cache_method(
3636 Returns:
3737 The decorator for caching methods.
3838 """
39+ cache_fn = _cache_function (cache )
40+ cache_key_fn = _cache_key_function (cache_args , require_hashable )
3941
4042 def cache_method_decorator (method : Callable ) -> Callable :
4143 """Decorator for caching method.
@@ -46,35 +48,10 @@ def cache_method_decorator(method: Callable) -> Callable:
4648 Returns:
4749 The wrapped cached method.
4850 """
49- # Function for returning cache key
50- cache_key_fn = _cache_key_function (cache_args , require_hashable )
51-
52- # Function for returning cache dict
53- if isinstance (cache , str ):
54-
55- def _cache_fn (self , method ):
56- if not hasattr (self , cache ):
57- setattr (self , cache , {})
58- instance_cache = getattr (self , cache )
59- name = method .__name__
60- if name not in instance_cache :
61- instance_cache [name ] = {}
62- return instance_cache [name ]
63-
64- else :
65-
66- def _cache_fn (self , method ):
67- # pylint: disable = unused-argument
68- name = method .__name__
69- if name not in cache :
70- cache [name ] = {}
71- return cache [name ]
72-
73- # Cached method function
7451
7552 @functools .wraps (method )
7653 def _cached_method (self , * args , ** kwargs ):
77- meth_cache = _cache_fn (self , method )
54+ meth_cache = cache_fn (self , method )
7855 key = cache_key_fn (* args , ** kwargs )
7956 if key in meth_cache :
8057 return meth_cache [key ]
@@ -87,7 +64,7 @@ def _cached_method(self, *args, **kwargs):
8764 return cache_method_decorator
8865
8966
90- def _cache_key_function (cache_args : bool = True , require_hashable : bool = True ) -> Callable :
67+ def _cache_key_function (cache_args : bool , require_hashable : bool ) -> Callable :
9168 """Return function for generating cache keys.
9269
9370 Args:
@@ -131,3 +108,37 @@ def _cache_key(*args, **kwargs):
131108 return cache_key
132109
133110 return _cache_key
111+
112+
113+ def _cache_function (cache : Union [Dict , str ]) -> Callable :
114+ """Return function for initializing and accessing cache dict.
115+
116+ Args:
117+ cache: The cache or cache attribute name to use. If a dict it will
118+ be used directly, if a str a cache dict will be created under
119+ that attribute name if one is not already present.
120+
121+ Returns:
122+ The function for accessing the cache dict.
123+ """
124+ if isinstance (cache , str ):
125+
126+ def _cache_fn (instance , method ):
127+ if not hasattr (instance , cache ):
128+ setattr (instance , cache , {})
129+ instance_cache = getattr (instance , cache )
130+ name = method .__name__
131+ if name not in instance_cache :
132+ instance_cache [name ] = {}
133+ return instance_cache [name ]
134+
135+ else :
136+
137+ def _cache_fn (instance , method ):
138+ # pylint: disable = unused-argument
139+ name = method .__name__
140+ if name not in cache :
141+ cache [name ] = {}
142+ return cache [name ]
143+
144+ return _cache_fn
0 commit comments