No need to rebuild a constant dictionary on every call. Move convert mapping to module level.

This commit is contained in:
Raymond Hettinger 2015-01-13 22:57:35 -08:00
parent e54dd0b92b
commit 1a8ada89f9
1 changed files with 17 additions and 16 deletions

View File

@ -174,9 +174,7 @@ def _lt_from_ge(self, other):
return op_result
return not op_result
def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
convert = {
_convert = {
'__lt__': [('__gt__', _gt_from_lt),
('__le__', _le_from_lt),
('__ge__', _ge_from_lt)],
@ -190,12 +188,15 @@ def total_ordering(cls):
('__gt__', _gt_from_ge),
('__lt__', _lt_from_ge)]
}
def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
# Find user-defined comparisons (not those inherited from object).
roots = [op for op in convert if getattr(cls, op, None) is not getattr(object, op, None)]
roots = [op for op in _convert if getattr(cls, op, None) is not getattr(object, op, None)]
if not roots:
raise ValueError('must define at least one ordering operation: < > <= >=')
root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
for opname, opfunc in convert[root]:
for opname, opfunc in _convert[root]:
if opname not in roots:
opfunc.__name__ = opname
setattr(cls, opname, opfunc)