Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 1 | """functools.py - Tools for working with functions and callable objects |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 2 | """ |
| 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 Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 7 | # and Raymond Hettinger <python at rcn.com> |
| 8 | # Copyright (C) 2006-2010 Python Software Foundation. |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 9 | # See C source code for _functools credits/copyright |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 10 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 11 | __all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', |
Benjamin Peterson | 1017ae5 | 2010-09-10 23:35:52 +0000 | [diff] [blame] | 12 | 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial'] |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 13 | |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 14 | from _functools import partial, reduce |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 15 | from collections import OrderedDict, namedtuple |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 16 | try: |
| 17 | from _thread import allocate_lock as Lock |
| 18 | except: |
| 19 | from _dummy_thread import allocate_lock as Lock |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 20 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 21 | # update_wrapper() and wraps() are tools to help write |
| 22 | # wrapper functions that can handle naive introspection |
| 23 | |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 24 | WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__') |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 25 | WRAPPER_UPDATES = ('__dict__',) |
| 26 | def 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 Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 37 | updated is a tuple naming the attributes of the wrapper that |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 38 | are updated with the corresponding attribute from the wrapped |
| 39 | function (defaults to functools.WRAPPER_UPDATES) |
| 40 | """ |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 41 | wrapper.__wrapped__ = wrapped |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 42 | for attr in assigned: |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 43 | try: |
| 44 | value = getattr(wrapped, attr) |
| 45 | except AttributeError: |
| 46 | pass |
| 47 | else: |
| 48 | setattr(wrapper, attr, value) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 49 | for attr in updated: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 50 | getattr(wrapper, attr).update(getattr(wrapped, attr, {})) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 51 | # Return the wrapper so this can be used as a decorator via partial() |
| 52 | return wrapper |
| 53 | |
| 54 | def 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 Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 67 | |
| 68 | def total_ordering(cls): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 69 | """Class decorator that fills in missing ordering methods""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 70 | convert = { |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 71 | '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), |
| 72 | ('__le__', lambda self, other: self < other or self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 73 | ('__ge__', lambda self, other: not self < other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 74 | '__le__': [('__ge__', lambda self, other: not self <= other or self == other), |
| 75 | ('__lt__', lambda self, other: self <= other and not self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 76 | ('__gt__', lambda self, other: not self <= other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 77 | '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), |
| 78 | ('__ge__', lambda self, other: self > other or self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 79 | ('__le__', lambda self, other: not self > other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 80 | '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), |
| 81 | ('__gt__', lambda self, other: self >= other and not self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 82 | ('__lt__', lambda self, other: not self >= other)] |
| 83 | } |
Raymond Hettinger | 3255c63 | 2010-09-16 00:31:21 +0000 | [diff] [blame] | 84 | # Find user-defined comparisons (not those inherited from object). |
Raymond Hettinger | 1006bd4 | 2010-09-14 22:55:13 +0000 | [diff] [blame] | 85 | roots = [op for op in convert if getattr(cls, op, None) is not getattr(object, op, None)] |
Raymond Hettinger | 56de7e2 | 2010-04-10 16:59:03 +0000 | [diff] [blame] | 86 | if not roots: |
| 87 | raise ValueError('must define at least one ordering operation: < > <= >=') |
| 88 | root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 89 | for opname, opfunc in convert[root]: |
| 90 | if opname not in roots: |
| 91 | opfunc.__name__ = opname |
| 92 | opfunc.__doc__ = getattr(int, opname).__doc__ |
| 93 | setattr(cls, opname, opfunc) |
| 94 | return cls |
| 95 | |
| 96 | def cmp_to_key(mycmp): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 97 | """Convert a cmp= function into a key= function""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 98 | class K(object): |
Raymond Hettinger | a0d1d96 | 2011-03-21 17:50:28 -0700 | [diff] [blame] | 99 | __slots__ = ['obj'] |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 100 | def __init__(self, obj): |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 101 | self.obj = obj |
| 102 | def __lt__(self, other): |
| 103 | return mycmp(self.obj, other.obj) < 0 |
| 104 | def __gt__(self, other): |
| 105 | return mycmp(self.obj, other.obj) > 0 |
| 106 | def __eq__(self, other): |
| 107 | return mycmp(self.obj, other.obj) == 0 |
| 108 | def __le__(self, other): |
| 109 | return mycmp(self.obj, other.obj) <= 0 |
| 110 | def __ge__(self, other): |
| 111 | return mycmp(self.obj, other.obj) >= 0 |
| 112 | def __ne__(self, other): |
| 113 | return mycmp(self.obj, other.obj) != 0 |
Raymond Hettinger | 003be52 | 2011-05-03 11:01:32 -0700 | [diff] [blame] | 114 | __hash__ = None |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 115 | return K |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 116 | |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 117 | try: |
| 118 | from _functools import cmp_to_key |
| 119 | except ImportError: |
| 120 | pass |
| 121 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 122 | _CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize") |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 123 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 124 | def lru_cache(maxsize=100, typed=False): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 125 | """Least-recently-used cache decorator. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 126 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 127 | If *maxsize* is set to None, the LRU features are disabled and the cache |
| 128 | can grow without bound. |
| 129 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 130 | If *typed* is True, arguments of different types will be cached separately. |
| 131 | For example, f(3.0) and f(3) will be treated as distinct calls with |
| 132 | distinct results. |
| 133 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 134 | Arguments to the cached function must be hashable. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 135 | |
Raymond Hettinger | 00f2f97 | 2010-12-01 00:47:56 +0000 | [diff] [blame] | 136 | View the cache statistics named tuple (hits, misses, maxsize, currsize) with |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 137 | f.cache_info(). Clear the cache and statistics with f.cache_clear(). |
Raymond Hettinger | 00f2f97 | 2010-12-01 00:47:56 +0000 | [diff] [blame] | 138 | Access the underlying function with f.__wrapped__. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 139 | |
| 140 | See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 141 | |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 142 | """ |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 143 | # Users should only access the lru_cache through its public API: |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 144 | # cache_info, cache_clear, and f.__wrapped__ |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 145 | # The internals of the lru_cache are encapsulated for thread safety and |
| 146 | # to allow the implementation to change (including a possible C version). |
| 147 | |
| 148 | def decorating_function(user_function, |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 149 | *, tuple=tuple, sorted=sorted, map=map, len=len, type=type, KeyError=KeyError): |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 150 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 151 | hits = misses = 0 |
Raymond Hettinger | 7e4c168 | 2011-03-18 15:09:10 -0700 | [diff] [blame] | 152 | kwd_mark = (object(),) # separates positional and keyword args |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 153 | lock = Lock() # needed because OrderedDict isn't threadsafe |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 154 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 155 | if maxsize is None: |
| 156 | cache = dict() # simple cache without ordering or size limit |
| 157 | |
| 158 | @wraps(user_function) |
| 159 | def wrapper(*args, **kwds): |
| 160 | nonlocal hits, misses |
| 161 | key = args |
| 162 | if kwds: |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 163 | sorted_items = tuple(sorted(kwds.items())) |
| 164 | key += kwd_mark + sorted_items |
| 165 | if typed: |
| 166 | key += tuple(map(type, args)) |
| 167 | if kwds: |
| 168 | key += tuple(type(v) for k, v in sorted_items) |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 169 | try: |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 170 | result = cache[key] |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 171 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 172 | return result |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 173 | except KeyError: |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 174 | pass |
| 175 | result = user_function(*args, **kwds) |
| 176 | cache[key] = result |
| 177 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 178 | return result |
| 179 | else: |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 180 | cache = OrderedDict() # ordered least recent to most recent |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 181 | cache_popitem = cache.popitem |
| 182 | cache_renew = cache.move_to_end |
| 183 | |
| 184 | @wraps(user_function) |
| 185 | def wrapper(*args, **kwds): |
| 186 | nonlocal hits, misses |
| 187 | key = args |
| 188 | if kwds: |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 189 | sorted_items = tuple(sorted(kwds.items())) |
| 190 | key += kwd_mark + sorted_items |
| 191 | if typed: |
| 192 | key += tuple(map(type, args)) |
| 193 | if kwds: |
| 194 | key += tuple(type(v) for k, v in sorted_items) |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 195 | with lock: |
| 196 | try: |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 197 | result = cache[key] |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 198 | cache_renew(key) # record recent use of this key |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 199 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 200 | return result |
| 201 | except KeyError: |
| 202 | pass |
| 203 | result = user_function(*args, **kwds) |
| 204 | with lock: |
| 205 | cache[key] = result # record recent use of this key |
| 206 | misses += 1 |
| 207 | if len(cache) > maxsize: |
| 208 | cache_popitem(0) # purge least recently used cache entry |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 209 | return result |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 210 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 211 | def cache_info(): |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 212 | """Report cache statistics""" |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 213 | with lock: |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 214 | return _CacheInfo(hits, misses, maxsize, len(cache)) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 215 | |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 216 | def cache_clear(): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 217 | """Clear the cache and cache statistics""" |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 218 | nonlocal hits, misses |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 219 | with lock: |
| 220 | cache.clear() |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 221 | hits = misses = 0 |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 222 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 223 | wrapper.cache_info = cache_info |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 224 | wrapper.cache_clear = cache_clear |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 225 | return wrapper |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 226 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 227 | return decorating_function |