-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmethodtools.py
80 lines (59 loc) · 2.33 KB
/
methodtools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
""":mod:`methodtools` --- functools for methods
===============================================
Expand functools features to methods, classmethods, staticmethods and even for
(unofficial) hybrid methods.
For now, methodtools only provides :func:`methodtools.lru_cache`.
Use methodtools module instead of functools module. Then it will work as you
expected - cache for each bound method.
.. code-block:: python
from methodtools import lru_cache
class A(object):
# cached method. the storage lifetime follows `self` object
@lru_cache()
def cached_method(self, args):
...
# cached classmethod. the storage lifetime follows `A` class
@lru_cache() # the order is important!
@classmethod # always lru_cache on top of classmethod
def cached_classmethod(self, args):
...
# cached staticmethod. the storage lifetime follows `A` class
@lru_cache() # the order is important!
@staticmethod # always lru_cache on top of staticmethod
def cached_staticmethod(self, args):
...
@lru_cache() # just same as functools.lru_cache
def cached_function():
...
"""
import functools
from wirerope import Wire, WireRope
__version__ = '0.4.7'
__all__ = 'lru_cache',
if hasattr(functools, 'lru_cache'):
_functools_lru_cache = functools.lru_cache
else:
try:
import functools32
except ImportError:
# raise AttributeError about fallback failure
functools.lru_cache # install `functools32` to run on py2
else:
_functools_lru_cache = functools32.lru_cache
class _LruCacheWire(Wire):
def __init__(self, rope, *args, **kwargs):
super(_LruCacheWire, self).__init__(rope, *args, **kwargs)
lru_args, lru_kwargs = rope._args
wrapper = _functools_lru_cache(
*lru_args, **lru_kwargs)(self.__func__)
self.__call__ = wrapper
self.cache_clear = wrapper.cache_clear
self.cache_info = wrapper.cache_info
def __call__(self, *args, **kwargs):
# descriptor detection support - never called
return self.__call__(*args, **kwargs)
def _on_property(self):
return self.__call__()
@functools.wraps(_functools_lru_cache)
def lru_cache(*args, **kwargs):
return WireRope(_LruCacheWire, wraps=True, rope_args=(args, kwargs))