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