Path: blob/master/elisp/emacs-for-python/rope-dist/rope/base/utils.py
1415 views
import warnings123def saveit(func):4"""A decorator that caches the return value of a function"""56name = '_' + func.__name__7def _wrapper(self, *args, **kwds):8if not hasattr(self, name):9setattr(self, name, func(self, *args, **kwds))10return getattr(self, name)11return _wrapper1213cacheit = saveit1415def prevent_recursion(default):16"""A decorator that returns the return value of `default` in recursions"""17def decorator(func):18name = '_calling_%s_' % func.__name__19def newfunc(self, *args, **kwds):20if getattr(self, name, False):21return default()22setattr(self, name, True)23try:24return func(self, *args, **kwds)25finally:26setattr(self, name, False)27return newfunc28return decorator293031def ignore_exception(exception_class):32"""A decorator that ignores `exception_class` exceptions"""33def _decorator(func):34def newfunc(*args, **kwds):35try:36return func(*args, **kwds)37except exception_class:38pass39return newfunc40return _decorator414243def deprecated(message=None):44"""A decorator for deprecated functions"""45def _decorator(func, message=message):46if message is None:47message = '%s is deprecated' % func.__name__48def newfunc(*args, **kwds):49warnings.warn(message, DeprecationWarning, stacklevel=2)50return func(*args, **kwds)51return newfunc52return _decorator535455def cached(count):56"""A caching decorator based on parameter objects"""57def decorator(func):58return _Cached(func, count)59return decorator6061class _Cached(object):6263def __init__(self, func, count):64self.func = func65self.cache = []66self.count = count6768def __call__(self, *args, **kwds):69key = (args, kwds)70for cached_key, cached_result in self.cache:71if cached_key == key:72return cached_result73result = self.func(*args, **kwds)74self.cache.append((key, result))75if len(self.cache) > self.count:76del self.cache[0]77return result787980