blob: 1effc08d9040f5110fb326650329ed7aef5cc69a [file] [log] [blame]
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001"""functools.py - Tools for working with functions and callable objects
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002"""
3# Python module wrapper for _functools C module
4# to allow utilities written in Python to be added
5# to the functools module.
6# Written by Nick Coghlan <ncoghlan at gmail.com>
Georg Brandl2e7346a2010-07-31 18:09:23 +00007# and Raymond Hettinger <python at rcn.com>
8# Copyright (C) 2006-2010 Python Software Foundation.
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00009# See C source code for _functools credits/copyright
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000010
Georg Brandl2e7346a2010-07-31 18:09:23 +000011__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
Raymond Hettinger0b5669c2010-08-15 07:41:40 +000012 'total_ordering', 'cmp_to_key', 'lru_cache']
Georg Brandl2e7346a2010-07-31 18:09:23 +000013
Guido van Rossum0919a1a2006-08-26 20:49:04 +000014from _functools import partial, reduce
Raymond Hettingerbc653d12010-08-15 03:35:24 +000015from collections import OrderedDict
Raymond Hettingercbe88132010-08-14 22:22:10 +000016try:
17 from _thread import allocate_lock as Lock
18except:
19 from _dummy_thread import allocate_lock as Lock
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000020
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000021# update_wrapper() and wraps() are tools to help write
22# wrapper functions that can handle naive introspection
23
Antoine Pitrou560f7642010-08-04 18:28:02 +000024WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__')
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000025WRAPPER_UPDATES = ('__dict__',)
26def update_wrapper(wrapper,
27 wrapped,
28 assigned = WRAPPER_ASSIGNMENTS,
29 updated = WRAPPER_UPDATES):
30 """Update a wrapper function to look like the wrapped function
31
32 wrapper is the function to be updated
33 wrapped is the original function
34 assigned is a tuple naming the attributes assigned directly
35 from the wrapped function to the wrapper function (defaults to
36 functools.WRAPPER_ASSIGNMENTS)
Thomas Wouters89f507f2006-12-13 04:49:30 +000037 updated is a tuple naming the attributes of the wrapper that
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000038 are updated with the corresponding attribute from the wrapped
39 function (defaults to functools.WRAPPER_UPDATES)
40 """
Nick Coghlan98876832010-08-17 06:17:18 +000041 wrapper.__wrapped__ = wrapped
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000042 for attr in assigned:
Nick Coghlan98876832010-08-17 06:17:18 +000043 try:
44 value = getattr(wrapped, attr)
45 except AttributeError:
46 pass
47 else:
48 setattr(wrapper, attr, value)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000049 for attr in updated:
Thomas Wouters89f507f2006-12-13 04:49:30 +000050 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000051 # Return the wrapper so this can be used as a decorator via partial()
52 return wrapper
53
54def wraps(wrapped,
55 assigned = WRAPPER_ASSIGNMENTS,
56 updated = WRAPPER_UPDATES):
57 """Decorator factory to apply update_wrapper() to a wrapper function
58
59 Returns a decorator that invokes update_wrapper() with the decorated
60 function as the wrapper argument and the arguments to wraps() as the
61 remaining arguments. Default arguments are as for update_wrapper().
62 This is a convenience function to simplify applying partial() to
63 update_wrapper().
64 """
65 return partial(update_wrapper, wrapped=wrapped,
66 assigned=assigned, updated=updated)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000067
Benjamin Peterson9c2930e2010-08-23 17:40:33 +000068_object_defaults = {object.__lt__, object.__le__, object.__gt__, object.__ge__}
Raymond Hettingerc50846a2010-04-05 18:56:31 +000069def total_ordering(cls):
Georg Brandle5a26732010-05-19 21:06:36 +000070 """Class decorator that fills in missing ordering methods"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +000071 convert = {
72 '__lt__': [('__gt__', lambda self, other: other < self),
73 ('__le__', lambda self, other: not other < self),
74 ('__ge__', lambda self, other: not self < other)],
75 '__le__': [('__ge__', lambda self, other: other <= self),
76 ('__lt__', lambda self, other: not other <= self),
77 ('__gt__', lambda self, other: not self <= other)],
78 '__gt__': [('__lt__', lambda self, other: other > self),
79 ('__ge__', lambda self, other: not other > self),
80 ('__le__', lambda self, other: not self > other)],
81 '__ge__': [('__le__', lambda self, other: other >= self),
82 ('__gt__', lambda self, other: not other >= self),
83 ('__lt__', lambda self, other: not self >= other)]
84 }
Benjamin Peterson16925e82010-08-24 21:30:14 +000085 roots = set(dir(cls)) & set(convert)
Benjamin Peterson9c2930e2010-08-23 17:40:33 +000086 # Remove default comparison operations defined on object.
87 roots -= {meth for meth in roots if getattr(cls, meth) in _object_defaults}
Raymond Hettinger56de7e22010-04-10 16:59:03 +000088 if not roots:
89 raise ValueError('must define at least one ordering operation: < > <= >=')
90 root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
Raymond Hettingerc50846a2010-04-05 18:56:31 +000091 for opname, opfunc in convert[root]:
92 if opname not in roots:
93 opfunc.__name__ = opname
94 opfunc.__doc__ = getattr(int, opname).__doc__
95 setattr(cls, opname, opfunc)
96 return cls
97
98def cmp_to_key(mycmp):
Georg Brandle5a26732010-05-19 21:06:36 +000099 """Convert a cmp= function into a key= function"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000100 class K(object):
101 def __init__(self, obj, *args):
102 self.obj = obj
103 def __lt__(self, other):
104 return mycmp(self.obj, other.obj) < 0
105 def __gt__(self, other):
106 return mycmp(self.obj, other.obj) > 0
107 def __eq__(self, other):
108 return mycmp(self.obj, other.obj) == 0
109 def __le__(self, other):
110 return mycmp(self.obj, other.obj) <= 0
111 def __ge__(self, other):
112 return mycmp(self.obj, other.obj) >= 0
113 def __ne__(self, other):
114 return mycmp(self.obj, other.obj) != 0
115 def __hash__(self):
116 raise TypeError('hash not implemented')
117 return K
Georg Brandl2e7346a2010-07-31 18:09:23 +0000118
Georg Brandl2e7346a2010-07-31 18:09:23 +0000119def lru_cache(maxsize=100):
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000120 """Least-recently-used cache decorator.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000121
122 Arguments to the cached function must be hashable.
123 Cache performance statistics stored in f.hits and f.misses.
124 Clear the cache using f.clear().
125 http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
126
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000127 """
Raymond Hettinger5202fad2010-08-14 22:29:52 +0000128 def decorating_function(user_function, tuple=tuple, sorted=sorted,
129 len=len, KeyError=KeyError):
Georg Brandl2e7346a2010-07-31 18:09:23 +0000130 cache = OrderedDict() # ordered least recent to most recent
Raymond Hettingeraf1e1402010-09-02 19:58:35 +0000131 cache_popitem = cache.popitem
132 cache_renew = cache._renew
Georg Brandl2e7346a2010-07-31 18:09:23 +0000133 kwd_mark = object() # separate positional and keyword args
Raymond Hettingercbe88132010-08-14 22:22:10 +0000134 lock = Lock()
Georg Brandl2e7346a2010-07-31 18:09:23 +0000135
136 @wraps(user_function)
137 def wrapper(*args, **kwds):
138 key = args
139 if kwds:
140 key += (kwd_mark,) + tuple(sorted(kwds.items()))
141 try:
Raymond Hettingercbe88132010-08-14 22:22:10 +0000142 with lock:
143 result = cache[key]
Raymond Hettinger7babc1b2010-09-02 19:56:28 +0000144 cache_renew(key) # record recent use of this key
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000145 wrapper.cache_hits += 1
Georg Brandl2e7346a2010-07-31 18:09:23 +0000146 except KeyError:
147 result = user_function(*args, **kwds)
Raymond Hettingercbe88132010-08-14 22:22:10 +0000148 with lock:
149 cache[key] = result # record recent use of this key
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000150 wrapper.cache_misses += 1
Raymond Hettingercbe88132010-08-14 22:22:10 +0000151 if len(cache) > maxsize:
Raymond Hettinger7babc1b2010-09-02 19:56:28 +0000152 cache_popitem(0) # purge least recently used cache entry
Georg Brandl2e7346a2010-07-31 18:09:23 +0000153 return result
154
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000155 def cache_clear():
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000156 """Clear the cache and cache statistics"""
Raymond Hettingercbe88132010-08-14 22:22:10 +0000157 with lock:
158 cache.clear()
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000159 wrapper.cache_hits = wrapper.cache_misses = 0
Georg Brandl2e7346a2010-07-31 18:09:23 +0000160
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000161 wrapper.cache_hits = wrapper.cache_misses = 0
162 wrapper.cache_clear = cache_clear
Georg Brandl2e7346a2010-07-31 18:09:23 +0000163 return wrapper
164 return decorating_function