blob: 0ac83d2bbf3ce9a161335509c162bcdbdb62f48b [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',
12 'total_ordering', 'cmp_to_key', 'lfu_cache', 'lru_cache']
13
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 """
41 for attr in assigned:
Antoine Pitrou560f7642010-08-04 18:28:02 +000042 if hasattr(wrapped, attr):
43 setattr(wrapper, attr, getattr(wrapped, attr))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000044 for attr in updated:
Thomas Wouters89f507f2006-12-13 04:49:30 +000045 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000046 # Return the wrapper so this can be used as a decorator via partial()
47 return wrapper
48
49def wraps(wrapped,
50 assigned = WRAPPER_ASSIGNMENTS,
51 updated = WRAPPER_UPDATES):
52 """Decorator factory to apply update_wrapper() to a wrapper function
53
54 Returns a decorator that invokes update_wrapper() with the decorated
55 function as the wrapper argument and the arguments to wraps() as the
56 remaining arguments. Default arguments are as for update_wrapper().
57 This is a convenience function to simplify applying partial() to
58 update_wrapper().
59 """
60 return partial(update_wrapper, wrapped=wrapped,
61 assigned=assigned, updated=updated)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000062
63def total_ordering(cls):
Georg Brandle5a26732010-05-19 21:06:36 +000064 """Class decorator that fills in missing ordering methods"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +000065 convert = {
66 '__lt__': [('__gt__', lambda self, other: other < self),
67 ('__le__', lambda self, other: not other < self),
68 ('__ge__', lambda self, other: not self < other)],
69 '__le__': [('__ge__', lambda self, other: other <= self),
70 ('__lt__', lambda self, other: not other <= self),
71 ('__gt__', lambda self, other: not self <= other)],
72 '__gt__': [('__lt__', lambda self, other: other > self),
73 ('__ge__', lambda self, other: not other > self),
74 ('__le__', lambda self, other: not self > other)],
75 '__ge__': [('__le__', lambda self, other: other >= self),
76 ('__gt__', lambda self, other: not other >= self),
77 ('__lt__', lambda self, other: not self >= other)]
78 }
79 roots = set(dir(cls)) & set(convert)
Raymond Hettinger56de7e22010-04-10 16:59:03 +000080 if not roots:
81 raise ValueError('must define at least one ordering operation: < > <= >=')
82 root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
Raymond Hettingerc50846a2010-04-05 18:56:31 +000083 for opname, opfunc in convert[root]:
84 if opname not in roots:
85 opfunc.__name__ = opname
86 opfunc.__doc__ = getattr(int, opname).__doc__
87 setattr(cls, opname, opfunc)
88 return cls
89
90def cmp_to_key(mycmp):
Georg Brandle5a26732010-05-19 21:06:36 +000091 """Convert a cmp= function into a key= function"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +000092 class K(object):
93 def __init__(self, obj, *args):
94 self.obj = obj
95 def __lt__(self, other):
96 return mycmp(self.obj, other.obj) < 0
97 def __gt__(self, other):
98 return mycmp(self.obj, other.obj) > 0
99 def __eq__(self, other):
100 return mycmp(self.obj, other.obj) == 0
101 def __le__(self, other):
102 return mycmp(self.obj, other.obj) <= 0
103 def __ge__(self, other):
104 return mycmp(self.obj, other.obj) >= 0
105 def __ne__(self, other):
106 return mycmp(self.obj, other.obj) != 0
107 def __hash__(self):
108 raise TypeError('hash not implemented')
109 return K
Georg Brandl2e7346a2010-07-31 18:09:23 +0000110
Georg Brandl2e7346a2010-07-31 18:09:23 +0000111def lru_cache(maxsize=100):
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000112 """Least-recently-used cache decorator.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000113
114 Arguments to the cached function must be hashable.
115 Cache performance statistics stored in f.hits and f.misses.
116 Clear the cache using f.clear().
117 http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
118
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000119 """
Raymond Hettinger5202fad2010-08-14 22:29:52 +0000120 def decorating_function(user_function, tuple=tuple, sorted=sorted,
121 len=len, KeyError=KeyError):
Georg Brandl2e7346a2010-07-31 18:09:23 +0000122 cache = OrderedDict() # ordered least recent to most recent
123 kwd_mark = object() # separate positional and keyword args
Raymond Hettingercbe88132010-08-14 22:22:10 +0000124 lock = Lock()
Georg Brandl2e7346a2010-07-31 18:09:23 +0000125
126 @wraps(user_function)
127 def wrapper(*args, **kwds):
128 key = args
129 if kwds:
130 key += (kwd_mark,) + tuple(sorted(kwds.items()))
131 try:
Raymond Hettingercbe88132010-08-14 22:22:10 +0000132 with lock:
133 result = cache[key]
134 del cache[key]
135 cache[key] = result # record recent use of this key
136 wrapper.hits += 1
Georg Brandl2e7346a2010-07-31 18:09:23 +0000137 except KeyError:
138 result = user_function(*args, **kwds)
Raymond Hettingercbe88132010-08-14 22:22:10 +0000139 with lock:
140 cache[key] = result # record recent use of this key
141 wrapper.misses += 1
142 if len(cache) > maxsize:
143 cache.popitem(0) # purge least recently used cache entry
Georg Brandl2e7346a2010-07-31 18:09:23 +0000144 return result
145
146 def clear():
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000147 """Clear the cache and cache statistics"""
Raymond Hettingercbe88132010-08-14 22:22:10 +0000148 with lock:
149 cache.clear()
150 wrapper.hits = wrapper.misses = 0
Georg Brandl2e7346a2010-07-31 18:09:23 +0000151
152 wrapper.hits = wrapper.misses = 0
153 wrapper.clear = clear
154 return wrapper
155 return decorating_function