blob: 53680b894660774d5c460c0198221d9444d23923 [file] [log] [blame]
Nick Coghlan676725d2006-06-08 13:54:49 +00001"""functools.py - Tools for working with functions and callable objects
Nick Coghlan08490142006-05-29 20:27:44 +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>
Nick Coghlan676725d2006-06-08 13:54:49 +00007# Copyright (C) 2006 Python Software Foundation.
8# See C source code for _functools credits/copyright
Nick Coghlan08490142006-05-29 20:27:44 +00009
Brett Cannon83e81842008-08-09 23:30:55 +000010from _functools import partial, reduce
Nick Coghlan08490142006-05-29 20:27:44 +000011
Nick Coghlan676725d2006-06-08 13:54:49 +000012# update_wrapper() and wraps() are tools to help write
13# wrapper functions that can handle naive introspection
14
15WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
16WRAPPER_UPDATES = ('__dict__',)
17def update_wrapper(wrapper,
18 wrapped,
19 assigned = WRAPPER_ASSIGNMENTS,
20 updated = WRAPPER_UPDATES):
21 """Update a wrapper function to look like the wrapped function
22
23 wrapper is the function to be updated
24 wrapped is the original function
25 assigned is a tuple naming the attributes assigned directly
26 from the wrapped function to the wrapper function (defaults to
27 functools.WRAPPER_ASSIGNMENTS)
Andrew M. Kuchlingefb57072006-10-26 19:16:46 +000028 updated is a tuple naming the attributes of the wrapper that
Nick Coghlan676725d2006-06-08 13:54:49 +000029 are updated with the corresponding attribute from the wrapped
30 function (defaults to functools.WRAPPER_UPDATES)
31 """
32 for attr in assigned:
33 setattr(wrapper, attr, getattr(wrapped, attr))
34 for attr in updated:
Andrew M. Kuchling41eb7162006-10-27 16:39:10 +000035 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Nick Coghlan676725d2006-06-08 13:54:49 +000036 # Return the wrapper so this can be used as a decorator via partial()
37 return wrapper
38
39def wraps(wrapped,
40 assigned = WRAPPER_ASSIGNMENTS,
41 updated = WRAPPER_UPDATES):
42 """Decorator factory to apply update_wrapper() to a wrapper function
43
44 Returns a decorator that invokes update_wrapper() with the decorated
45 function as the wrapper argument and the arguments to wraps() as the
46 remaining arguments. Default arguments are as for update_wrapper().
47 This is a convenience function to simplify applying partial() to
48 update_wrapper().
49 """
50 return partial(update_wrapper, wrapped=wrapped,
51 assigned=assigned, updated=updated)
Raymond Hettingera551f312010-04-04 18:34:45 +000052
53def total_ordering(cls):
Georg Brandlea567102010-04-14 08:56:01 +000054 """Class decorator that fills in missing ordering methods"""
Raymond Hettingera551f312010-04-04 18:34:45 +000055 convert = {
Éric Araujo374274d2011-03-19 04:29:36 +010056 '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
57 ('__le__', lambda self, other: self < other or self == other),
Raymond Hettingera551f312010-04-04 18:34:45 +000058 ('__ge__', lambda self, other: not self < other)],
Éric Araujo374274d2011-03-19 04:29:36 +010059 '__le__': [('__ge__', lambda self, other: not self <= other or self == other),
60 ('__lt__', lambda self, other: self <= other and not self == other),
Raymond Hettingera551f312010-04-04 18:34:45 +000061 ('__gt__', lambda self, other: not self <= other)],
Éric Araujo374274d2011-03-19 04:29:36 +010062 '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
63 ('__ge__', lambda self, other: self > other or self == other),
Raymond Hettingera551f312010-04-04 18:34:45 +000064 ('__le__', lambda self, other: not self > other)],
Éric Araujo374274d2011-03-19 04:29:36 +010065 '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
66 ('__gt__', lambda self, other: self >= other and not self == other),
Raymond Hettingera551f312010-04-04 18:34:45 +000067 ('__lt__', lambda self, other: not self >= other)]
68 }
69 roots = set(dir(cls)) & set(convert)
Raymond Hettinger4e455122010-04-10 16:57:36 +000070 if not roots:
71 raise ValueError('must define at least one ordering operation: < > <= >=')
72 root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
Raymond Hettingera551f312010-04-04 18:34:45 +000073 for opname, opfunc in convert[root]:
74 if opname not in roots:
75 opfunc.__name__ = opname
76 opfunc.__doc__ = getattr(int, opname).__doc__
77 setattr(cls, opname, opfunc)
78 return cls
79
Raymond Hettingerbb006cf2010-04-04 21:45:01 +000080def cmp_to_key(mycmp):
Georg Brandlea567102010-04-14 08:56:01 +000081 """Convert a cmp= function into a key= function"""
Raymond Hettingera551f312010-04-04 18:34:45 +000082 class K(object):
Raymond Hettinger911da472011-03-22 13:20:59 -070083 __slots__ = ['obj']
Raymond Hettingera551f312010-04-04 18:34:45 +000084 def __init__(self, obj, *args):
85 self.obj = obj
86 def __lt__(self, other):
87 return mycmp(self.obj, other.obj) < 0
88 def __gt__(self, other):
89 return mycmp(self.obj, other.obj) > 0
90 def __eq__(self, other):
91 return mycmp(self.obj, other.obj) == 0
92 def __le__(self, other):
93 return mycmp(self.obj, other.obj) <= 0
94 def __ge__(self, other):
95 return mycmp(self.obj, other.obj) >= 0
96 def __ne__(self, other):
97 return mycmp(self.obj, other.obj) != 0
Raymond Hettingere1d665a2010-04-05 18:53:43 +000098 def __hash__(self):
99 raise TypeError('hash not implemented')
Raymond Hettingera551f312010-04-04 18:34:45 +0000100 return K