Skip to content

Instantly share code, notes, and snippets.

@jml
Created August 3, 2015 12:45
Show Gist options
  • Select an option

  • Save jml/3a18f056504d37a7df40 to your computer and use it in GitHub Desktop.

Select an option

Save jml/3a18f056504d37a7df40 to your computer and use it in GitHub Desktop.
def orderable(*attributes):
def wrap(cl):
cl = _add_cmp(cl, attrs=attributes)
return cl
return wrap
def _attrs_to_tuple(obj, attrs):
"""
Create a tuple of values of *obj*'s *attributes*.
"""
return tuple(getattr(obj, a) for a in attrs)
def _add_cmp(cl, attrs):
"""
Add comparison methods to *cl*.
"""
def attrs_to_tuple(obj):
"""
Save us some typing.
"""
return _attrs_to_tuple(obj, attrs)
def eq(self, other):
"""
Automatically created by attrs.
"""
if other.__class__ is self.__class__:
return attrs_to_tuple(self) == attrs_to_tuple(other)
else:
return NotImplemented
def ne(self, other):
"""
Automatically created by attrs.
"""
result = eq(self, other)
if result is NotImplemented:
return NotImplemented
else:
return not result
def lt(self, other):
"""
Automatically created by attrs.
"""
if isinstance(other, self.__class__):
return attrs_to_tuple(self) < attrs_to_tuple(other)
else:
return NotImplemented
def le(self, other):
"""
Automatically created by attrs.
"""
if isinstance(other, self.__class__):
return attrs_to_tuple(self) <= attrs_to_tuple(other)
else:
return NotImplemented
def gt(self, other):
"""
Automatically created by attrs.
"""
if isinstance(other, self.__class__):
return attrs_to_tuple(self) > attrs_to_tuple(other)
else:
return NotImplemented
def ge(self, other):
"""
Automatically created by attrs.
"""
if isinstance(other, self.__class__):
return attrs_to_tuple(self) >= attrs_to_tuple(other)
else:
return NotImplemented
cl.__eq__ = eq
cl.__ne__ = ne
cl.__lt__ = lt
cl.__le__ = le
cl.__gt__ = gt
cl.__ge__ = ge
return cl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment