blob: adc79274ca34860339de1a651527e58c4aa8272f [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',
Benjamin Peterson1017ae52010-09-10 23:35:52 +000012 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial']
Georg Brandl2e7346a2010-07-31 18:09:23 +000013
Guido van Rossum0919a1a2006-08-26 20:49:04 +000014from _functools import partial, reduce
Raymond Hettingerec0e9102012-03-16 01:16:31 -070015from collections import namedtuple
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
Meador Ingeff7f64c2011-12-11 22:37:31 -060024WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
25 '__annotations__')
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000026WRAPPER_UPDATES = ('__dict__',)
27def update_wrapper(wrapper,
28 wrapped,
29 assigned = WRAPPER_ASSIGNMENTS,
30 updated = WRAPPER_UPDATES):
31 """Update a wrapper function to look like the wrapped function
32
33 wrapper is the function to be updated
34 wrapped is the original function
35 assigned is a tuple naming the attributes assigned directly
36 from the wrapped function to the wrapper function (defaults to
37 functools.WRAPPER_ASSIGNMENTS)
Thomas Wouters89f507f2006-12-13 04:49:30 +000038 updated is a tuple naming the attributes of the wrapper that
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000039 are updated with the corresponding attribute from the wrapped
40 function (defaults to functools.WRAPPER_UPDATES)
41 """
Nick Coghlan98876832010-08-17 06:17:18 +000042 wrapper.__wrapped__ = wrapped
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000043 for attr in assigned:
Nick Coghlan98876832010-08-17 06:17:18 +000044 try:
45 value = getattr(wrapped, attr)
46 except AttributeError:
47 pass
48 else:
49 setattr(wrapper, attr, value)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000050 for attr in updated:
Thomas Wouters89f507f2006-12-13 04:49:30 +000051 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000052 # Return the wrapper so this can be used as a decorator via partial()
53 return wrapper
54
55def wraps(wrapped,
56 assigned = WRAPPER_ASSIGNMENTS,
57 updated = WRAPPER_UPDATES):
58 """Decorator factory to apply update_wrapper() to a wrapper function
59
60 Returns a decorator that invokes update_wrapper() with the decorated
61 function as the wrapper argument and the arguments to wraps() as the
62 remaining arguments. Default arguments are as for update_wrapper().
63 This is a convenience function to simplify applying partial() to
64 update_wrapper().
65 """
66 return partial(update_wrapper, wrapped=wrapped,
67 assigned=assigned, updated=updated)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000068
69def 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 = {
Raymond Hettinger23f9fc32011-01-08 07:01:56 +000072 '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
73 ('__le__', lambda self, other: self < other or self == other),
Raymond Hettingerc50846a2010-04-05 18:56:31 +000074 ('__ge__', lambda self, other: not self < other)],
Raymond Hettinger23f9fc32011-01-08 07:01:56 +000075 '__le__': [('__ge__', lambda self, other: not self <= other or self == other),
76 ('__lt__', lambda self, other: self <= other and not self == other),
Raymond Hettingerc50846a2010-04-05 18:56:31 +000077 ('__gt__', lambda self, other: not self <= other)],
Raymond Hettinger23f9fc32011-01-08 07:01:56 +000078 '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
79 ('__ge__', lambda self, other: self > other or self == other),
Raymond Hettingerc50846a2010-04-05 18:56:31 +000080 ('__le__', lambda self, other: not self > other)],
Raymond Hettinger23f9fc32011-01-08 07:01:56 +000081 '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
82 ('__gt__', lambda self, other: self >= other and not self == other),
Raymond Hettingerc50846a2010-04-05 18:56:31 +000083 ('__lt__', lambda self, other: not self >= other)]
84 }
Raymond Hettinger3255c632010-09-16 00:31:21 +000085 # Find user-defined comparisons (not those inherited from object).
Raymond Hettinger1006bd42010-09-14 22:55:13 +000086 roots = [op for op in convert if getattr(cls, op, None) is not getattr(object, op, None)]
Raymond Hettinger56de7e22010-04-10 16:59:03 +000087 if not roots:
88 raise ValueError('must define at least one ordering operation: < > <= >=')
89 root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
Raymond Hettingerc50846a2010-04-05 18:56:31 +000090 for opname, opfunc in convert[root]:
91 if opname not in roots:
92 opfunc.__name__ = opname
93 opfunc.__doc__ = getattr(int, opname).__doc__
94 setattr(cls, opname, opfunc)
95 return cls
96
97def cmp_to_key(mycmp):
Georg Brandle5a26732010-05-19 21:06:36 +000098 """Convert a cmp= function into a key= function"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +000099 class K(object):
Raymond Hettingera0d1d962011-03-21 17:50:28 -0700100 __slots__ = ['obj']
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700101 def __init__(self, obj):
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000102 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
Raymond Hettinger003be522011-05-03 11:01:32 -0700115 __hash__ = None
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000116 return K
Georg Brandl2e7346a2010-07-31 18:09:23 +0000117
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700118try:
119 from _functools import cmp_to_key
120except ImportError:
121 pass
122
Raymond Hettinger7496b412010-11-30 19:15:45 +0000123_CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize")
Nick Coghlan234515a2010-11-30 06:19:46 +0000124
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700125def lru_cache(maxsize=100, typed=False):
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000126 """Least-recently-used cache decorator.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000127
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000128 If *maxsize* is set to None, the LRU features are disabled and the cache
129 can grow without bound.
130
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700131 If *typed* is True, arguments of different types will be cached separately.
132 For example, f(3.0) and f(3) will be treated as distinct calls with
133 distinct results.
134
Georg Brandl2e7346a2010-07-31 18:09:23 +0000135 Arguments to the cached function must be hashable.
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000136
Raymond Hettinger00f2f972010-12-01 00:47:56 +0000137 View the cache statistics named tuple (hits, misses, maxsize, currsize) with
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000138 f.cache_info(). Clear the cache and statistics with f.cache_clear().
Raymond Hettinger00f2f972010-12-01 00:47:56 +0000139 Access the underlying function with f.__wrapped__.
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000140
141 See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
Georg Brandl2e7346a2010-07-31 18:09:23 +0000142
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000143 """
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000144 # Users should only access the lru_cache through its public API:
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000145 # cache_info, cache_clear, and f.__wrapped__
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000146 # The internals of the lru_cache are encapsulated for thread safety and
147 # to allow the implementation to change (including a possible C version).
148
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700149 def decorating_function(user_function):
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000150
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700151 cache = dict()
Nick Coghlan234515a2010-11-30 06:19:46 +0000152 hits = misses = 0
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700153 cache_get = cache.get # bound method to lookup key or return None
154 _len = len # localize the global len() function
155 kwd_mark = (object(),) # separate positional and keyword args
156 lock = Lock() # because linkedlist updates aren't threadsafe
157 root = [] # root of the circular doubly linked list
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700158 root[:] = [root, root, None, None] # initialize by pointing to self
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700159 PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
160
161 def make_key(args, kwds, typed, tuple=tuple, sorted=sorted, type=type):
162 key = args
163 if kwds:
164 sorted_items = tuple(sorted(kwds.items()))
165 key += kwd_mark + sorted_items
166 if typed:
167 key += tuple(type(v) for v in args)
168 if kwds:
169 key += tuple(type(v) for k, v in sorted_items)
170 return key
Georg Brandl2e7346a2010-07-31 18:09:23 +0000171
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000172 if maxsize is None:
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000173 @wraps(user_function)
174 def wrapper(*args, **kwds):
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700175 # simple caching without ordering or size limit
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000176 nonlocal hits, misses
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700177 key = make_key(args, kwds, typed) if kwds or typed else args
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700178 result = cache_get(key)
179 if result is not None:
Nick Coghlan234515a2010-11-30 06:19:46 +0000180 hits += 1
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700181 return result
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700182 result = user_function(*args, **kwds)
183 cache[key] = result
184 misses += 1
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000185 return result
186 else:
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000187 @wraps(user_function)
188 def wrapper(*args, **kwds):
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700189 # size limited caching that tracks accesses by recency
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000190 nonlocal hits, misses
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700191 key = make_key(args, kwds, typed) if kwds or typed else args
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700192 with lock:
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700193 link = cache_get(key)
194 if link is not None:
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700195 # record recent use of the key by moving it to the front of the list
196 link_prev, link_next, key, result = link
197 link_prev[NEXT] = link_next
198 link_next[PREV] = link_prev
199 last = root[PREV]
200 last[NEXT] = root[PREV] = link
201 link[PREV] = last
202 link[NEXT] = root
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000203 hits += 1
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700204 return result
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700205 result = user_function(*args, **kwds)
206 with lock:
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700207 last = root[PREV]
208 link = [last, root, key, result]
209 cache[key] = last[NEXT] = root[PREV] = link
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700210 if _len(cache) > maxsize:
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700211 # purge least recently used cache entry
212 old_prev, old_next, old_key, old_result = root[NEXT]
213 root[NEXT] = old_next
214 old_next[PREV] = root
215 del cache[old_key]
216 misses += 1
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000217 return result
Georg Brandl2e7346a2010-07-31 18:09:23 +0000218
Nick Coghlan234515a2010-11-30 06:19:46 +0000219 def cache_info():
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000220 """Report cache statistics"""
Nick Coghlan234515a2010-11-30 06:19:46 +0000221 with lock:
Raymond Hettinger7496b412010-11-30 19:15:45 +0000222 return _CacheInfo(hits, misses, maxsize, len(cache))
Nick Coghlan234515a2010-11-30 06:19:46 +0000223
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000224 def cache_clear():
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000225 """Clear the cache and cache statistics"""
Benjamin Peterson954cf572012-03-16 18:22:26 -0500226 nonlocal hits, misses, root
Raymond Hettingercbe88132010-08-14 22:22:10 +0000227 with lock:
228 cache.clear()
Benjamin Peterson954cf572012-03-16 18:22:26 -0500229 root[:] = [root, root, None, None]
Nick Coghlan234515a2010-11-30 06:19:46 +0000230 hits = misses = 0
Georg Brandl2e7346a2010-07-31 18:09:23 +0000231
Nick Coghlan234515a2010-11-30 06:19:46 +0000232 wrapper.cache_info = cache_info
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000233 wrapper.cache_clear = cache_clear
Georg Brandl2e7346a2010-07-31 18:09:23 +0000234 return wrapper
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000235
Georg Brandl2e7346a2010-07-31 18:09:23 +0000236 return decorating_function