Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
marvel
GitHub Repository: marvel/qnf
Path: blob/master/elisp/emacs-for-python/rope-dist/rope/base/utils.py
1415 views
1
import warnings
2
3
4
def saveit(func):
5
"""A decorator that caches the return value of a function"""
6
7
name = '_' + func.__name__
8
def _wrapper(self, *args, **kwds):
9
if not hasattr(self, name):
10
setattr(self, name, func(self, *args, **kwds))
11
return getattr(self, name)
12
return _wrapper
13
14
cacheit = saveit
15
16
def prevent_recursion(default):
17
"""A decorator that returns the return value of `default` in recursions"""
18
def decorator(func):
19
name = '_calling_%s_' % func.__name__
20
def newfunc(self, *args, **kwds):
21
if getattr(self, name, False):
22
return default()
23
setattr(self, name, True)
24
try:
25
return func(self, *args, **kwds)
26
finally:
27
setattr(self, name, False)
28
return newfunc
29
return decorator
30
31
32
def ignore_exception(exception_class):
33
"""A decorator that ignores `exception_class` exceptions"""
34
def _decorator(func):
35
def newfunc(*args, **kwds):
36
try:
37
return func(*args, **kwds)
38
except exception_class:
39
pass
40
return newfunc
41
return _decorator
42
43
44
def deprecated(message=None):
45
"""A decorator for deprecated functions"""
46
def _decorator(func, message=message):
47
if message is None:
48
message = '%s is deprecated' % func.__name__
49
def newfunc(*args, **kwds):
50
warnings.warn(message, DeprecationWarning, stacklevel=2)
51
return func(*args, **kwds)
52
return newfunc
53
return _decorator
54
55
56
def cached(count):
57
"""A caching decorator based on parameter objects"""
58
def decorator(func):
59
return _Cached(func, count)
60
return decorator
61
62
class _Cached(object):
63
64
def __init__(self, func, count):
65
self.func = func
66
self.cache = []
67
self.count = count
68
69
def __call__(self, *args, **kwds):
70
key = (args, kwds)
71
for cached_key, cached_result in self.cache:
72
if cached_key == key:
73
return cached_result
74
result = self.func(*args, **kwds)
75
self.cache.append((key, result))
76
if len(self.cache) > self.count:
77
del self.cache[0]
78
return result
79
80