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', |
| 12 | 'total_ordering', 'cmp_to_key', 'lfu_cache', 'lru_cache'] |
| 13 | |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 14 | from _functools import partial, reduce |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 15 | from collections import OrderedDict, Counter |
| 16 | from heapq import nsmallest |
| 17 | from operator import itemgetter |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 18 | try: |
| 19 | from _thread import allocate_lock as Lock |
| 20 | except: |
| 21 | from _dummy_thread import allocate_lock as Lock |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 22 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 23 | # update_wrapper() and wraps() are tools to help write |
| 24 | # wrapper functions that can handle naive introspection |
| 25 | |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 26 | WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__', '__annotations__') |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 27 | WRAPPER_UPDATES = ('__dict__',) |
| 28 | def update_wrapper(wrapper, |
| 29 | wrapped, |
| 30 | assigned = WRAPPER_ASSIGNMENTS, |
| 31 | updated = WRAPPER_UPDATES): |
| 32 | """Update a wrapper function to look like the wrapped function |
| 33 | |
| 34 | wrapper is the function to be updated |
| 35 | wrapped is the original function |
| 36 | assigned is a tuple naming the attributes assigned directly |
| 37 | from the wrapped function to the wrapper function (defaults to |
| 38 | functools.WRAPPER_ASSIGNMENTS) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 39 | updated is a tuple naming the attributes of the wrapper that |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 40 | are updated with the corresponding attribute from the wrapped |
| 41 | function (defaults to functools.WRAPPER_UPDATES) |
| 42 | """ |
| 43 | for attr in assigned: |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 44 | if hasattr(wrapped, attr): |
| 45 | setattr(wrapper, attr, getattr(wrapped, attr)) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 46 | for attr in updated: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 47 | getattr(wrapper, attr).update(getattr(wrapped, attr, {})) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 48 | # Return the wrapper so this can be used as a decorator via partial() |
| 49 | return wrapper |
| 50 | |
| 51 | def wraps(wrapped, |
| 52 | assigned = WRAPPER_ASSIGNMENTS, |
| 53 | updated = WRAPPER_UPDATES): |
| 54 | """Decorator factory to apply update_wrapper() to a wrapper function |
| 55 | |
| 56 | Returns a decorator that invokes update_wrapper() with the decorated |
| 57 | function as the wrapper argument and the arguments to wraps() as the |
| 58 | remaining arguments. Default arguments are as for update_wrapper(). |
| 59 | This is a convenience function to simplify applying partial() to |
| 60 | update_wrapper(). |
| 61 | """ |
| 62 | return partial(update_wrapper, wrapped=wrapped, |
| 63 | assigned=assigned, updated=updated) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 64 | |
| 65 | def total_ordering(cls): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 66 | """Class decorator that fills in missing ordering methods""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 67 | convert = { |
| 68 | '__lt__': [('__gt__', lambda self, other: other < self), |
| 69 | ('__le__', lambda self, other: not other < self), |
| 70 | ('__ge__', lambda self, other: not self < other)], |
| 71 | '__le__': [('__ge__', lambda self, other: other <= self), |
| 72 | ('__lt__', lambda self, other: not other <= self), |
| 73 | ('__gt__', lambda self, other: not self <= other)], |
| 74 | '__gt__': [('__lt__', lambda self, other: other > self), |
| 75 | ('__ge__', lambda self, other: not other > self), |
| 76 | ('__le__', lambda self, other: not self > other)], |
| 77 | '__ge__': [('__le__', lambda self, other: other >= self), |
| 78 | ('__gt__', lambda self, other: not other >= self), |
| 79 | ('__lt__', lambda self, other: not self >= other)] |
| 80 | } |
| 81 | roots = set(dir(cls)) & set(convert) |
Raymond Hettinger | 56de7e2 | 2010-04-10 16:59:03 +0000 | [diff] [blame] | 82 | if not roots: |
| 83 | raise ValueError('must define at least one ordering operation: < > <= >=') |
| 84 | root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 85 | for opname, opfunc in convert[root]: |
| 86 | if opname not in roots: |
| 87 | opfunc.__name__ = opname |
| 88 | opfunc.__doc__ = getattr(int, opname).__doc__ |
| 89 | setattr(cls, opname, opfunc) |
| 90 | return cls |
| 91 | |
| 92 | def cmp_to_key(mycmp): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 93 | """Convert a cmp= function into a key= function""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 94 | class K(object): |
| 95 | def __init__(self, obj, *args): |
| 96 | self.obj = obj |
| 97 | def __lt__(self, other): |
| 98 | return mycmp(self.obj, other.obj) < 0 |
| 99 | def __gt__(self, other): |
| 100 | return mycmp(self.obj, other.obj) > 0 |
| 101 | def __eq__(self, other): |
| 102 | return mycmp(self.obj, other.obj) == 0 |
| 103 | def __le__(self, other): |
| 104 | return mycmp(self.obj, other.obj) <= 0 |
| 105 | def __ge__(self, other): |
| 106 | return mycmp(self.obj, other.obj) >= 0 |
| 107 | def __ne__(self, other): |
| 108 | return mycmp(self.obj, other.obj) != 0 |
| 109 | def __hash__(self): |
| 110 | raise TypeError('hash not implemented') |
| 111 | return K |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 112 | |
| 113 | def lfu_cache(maxsize=100): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 114 | """Least-frequently-used cache decorator. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 115 | |
| 116 | Arguments to the cached function must be hashable. |
| 117 | Cache performance statistics stored in f.hits and f.misses. |
| 118 | Clear the cache using f.clear(). |
| 119 | http://en.wikipedia.org/wiki/Cache_algorithms#Least-Frequently_Used |
| 120 | |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 121 | """ |
Raymond Hettinger | 5202fad | 2010-08-14 22:29:52 +0000 | [diff] [blame] | 122 | def decorating_function(user_function, tuple=tuple, sorted=sorted, |
| 123 | len=len, KeyError=KeyError): |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 124 | cache = {} # mapping of args to results |
| 125 | use_count = Counter() # times each key has been accessed |
| 126 | kwd_mark = object() # separate positional and keyword args |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 127 | lock = Lock() |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 128 | |
| 129 | @wraps(user_function) |
| 130 | def wrapper(*args, **kwds): |
| 131 | key = args |
| 132 | if kwds: |
| 133 | key += (kwd_mark,) + tuple(sorted(kwds.items())) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 134 | try: |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 135 | with lock: |
| 136 | use_count[key] += 1 # count a use of this key |
| 137 | result = cache[key] |
| 138 | wrapper.hits += 1 |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 139 | except KeyError: |
| 140 | result = user_function(*args, **kwds) |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 141 | with lock: |
| 142 | use_count[key] += 1 # count a use of this key |
| 143 | cache[key] = result |
| 144 | wrapper.misses += 1 |
| 145 | if len(cache) > maxsize: |
| 146 | # purge the 10% least frequently used entries |
Raymond Hettinger | 0f56e90 | 2010-08-14 23:52:08 +0000 | [diff] [blame^] | 147 | for key, _ in nsmallest(maxsize // 10 or 1, |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 148 | use_count.items(), |
| 149 | key=itemgetter(1)): |
| 150 | del cache[key], use_count[key] |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 151 | return result |
| 152 | |
| 153 | def clear(): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 154 | """Clear the cache and cache statistics""" |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 155 | with lock: |
| 156 | cache.clear() |
| 157 | use_count.clear() |
| 158 | wrapper.hits = wrapper.misses = 0 |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 159 | |
| 160 | wrapper.hits = wrapper.misses = 0 |
| 161 | wrapper.clear = clear |
| 162 | return wrapper |
| 163 | return decorating_function |
| 164 | |
| 165 | def lru_cache(maxsize=100): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 166 | """Least-recently-used cache decorator. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 167 | |
| 168 | Arguments to the cached function must be hashable. |
| 169 | Cache performance statistics stored in f.hits and f.misses. |
| 170 | Clear the cache using f.clear(). |
| 171 | http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used |
| 172 | |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 173 | """ |
Raymond Hettinger | 5202fad | 2010-08-14 22:29:52 +0000 | [diff] [blame] | 174 | def decorating_function(user_function, tuple=tuple, sorted=sorted, |
| 175 | len=len, KeyError=KeyError): |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 176 | cache = OrderedDict() # ordered least recent to most recent |
| 177 | kwd_mark = object() # separate positional and keyword args |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 178 | lock = Lock() |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 179 | |
| 180 | @wraps(user_function) |
| 181 | def wrapper(*args, **kwds): |
| 182 | key = args |
| 183 | if kwds: |
| 184 | key += (kwd_mark,) + tuple(sorted(kwds.items())) |
| 185 | try: |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 186 | with lock: |
| 187 | result = cache[key] |
| 188 | del cache[key] |
| 189 | cache[key] = result # record recent use of this key |
| 190 | wrapper.hits += 1 |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 191 | except KeyError: |
| 192 | result = user_function(*args, **kwds) |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 193 | with lock: |
| 194 | cache[key] = result # record recent use of this key |
| 195 | wrapper.misses += 1 |
| 196 | if len(cache) > maxsize: |
| 197 | cache.popitem(0) # purge least recently used cache entry |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 198 | return result |
| 199 | |
| 200 | def clear(): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 201 | """Clear the cache and cache statistics""" |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 202 | with lock: |
| 203 | cache.clear() |
| 204 | wrapper.hits = wrapper.misses = 0 |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 205 | |
| 206 | wrapper.hits = wrapper.misses = 0 |
| 207 | wrapper.clear = clear |
| 208 | return wrapper |
| 209 | return decorating_function |