Changeset 391 for python/trunk/Lib/functools.py
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/functools.py
r2 r391 50 50 return partial(update_wrapper, wrapped=wrapped, 51 51 assigned=assigned, updated=updated) 52 53 def total_ordering(cls): 54 """Class decorator that fills in missing ordering methods""" 55 convert = { 56 '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), 57 ('__le__', lambda self, other: self < other or self == other), 58 ('__ge__', lambda self, other: not self < other)], 59 '__le__': [('__ge__', lambda self, other: not self <= other or self == other), 60 ('__lt__', lambda self, other: self <= other and not self == other), 61 ('__gt__', lambda self, other: not self <= other)], 62 '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), 63 ('__ge__', lambda self, other: self > other or self == other), 64 ('__le__', lambda self, other: not self > other)], 65 '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), 66 ('__gt__', lambda self, other: self >= other and not self == other), 67 ('__lt__', lambda self, other: not self >= other)] 68 } 69 roots = set(dir(cls)) & set(convert) 70 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__ 73 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 80 def cmp_to_key(mycmp): 81 """Convert a cmp= function into a key= function""" 82 class K(object): 83 __slots__ = ['obj'] 84 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 98 def __hash__(self): 99 raise TypeError('hash not implemented') 100 return K
Note:
See TracChangeset
for help on using the changeset viewer.