decorators: Replace 'FunctionMaker' with a simple function
[git-cola.git] / cola / decorators.py
blob0587a964615c5071d1ff6b6175e3284a2c92ff80
1 __all__ = ('decorator', 'deprecated', 'memoize')
4 def decorator(caller, func=None):
5 """
6 decorator(caller) converts a caller function into a decorator;
7 decorator(caller, func) decorates a function using a caller.
8 """
9 if func is None: # returns a decorator
10 def _decorator(f, *args, **opts):
11 def _caller(*args, **opts):
12 return caller(f, *args, **opts)
13 return _caller
14 return _decorator
16 else: # returns a decorated function
17 def _decorator(*args, **opts):
18 return caller(func, *args, **opts)
19 return _decorator
22 @decorator
23 def deprecated(func, *args, **kw):
24 "A decorator for deprecated functions"
25 import warnings
26 warnings.warn('Calling deprecated function %r' % func.__name__,
27 DeprecationWarning, stacklevel=3)
28 return func(*args, **kw)
31 def memoize(func):
32 """
33 A decorator for memoizing function calls
35 http://en.wikipedia.org/wiki/Memoization
37 """
38 func.cache = {}
39 return decorator(_memoize, func)
42 def _memoize(func, *args, **opts):
43 """Implements memoized cache lookups"""
44 if opts: # frozenset is used to ensure hashability
45 key = args, frozenset(opts.items())
46 else:
47 key = args
48 cache = func.cache # attribute added by memoize
49 try:
50 return cache[key]
51 except KeyError:
52 cache[key] = result = func(*args, **opts)
53 return result