Skip to content

Instantly share code, notes, and snippets.

@m1el
Last active May 29, 2021 20:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1el/0ab86f8b0c8736a3090ce36d9d0d5851 to your computer and use it in GitHub Desktop.
Save m1el/0ab86f8b0c8736a3090ce36d9d0d5851 to your computer and use it in GitHub Desktop.
Python wrapper for reverse ordering of a value.
class Reverse(object):
'''
Wrapper for reverse ordering of a value.
Usage:
array = [1, 2, 3, 4]
array.sort(key=Reverse)
# [4, 3, 2, 1]
from collections import namedtuple
Student = namedtuple('Student', ['name', 'mark'])
array = [Student('John', 4), Student('Jeane', 4), Student('John', 3)]
array.sort(key=lambda student: (Reverse(student.mark), student.name))
# [Student('Jeane', 4), Student('John', 4), Student('John', 3)]
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return f'Reverse({self.value!r})'
def _type_guard(self, sign, other):
if not isinstance(other, Reverse):
raise TypeError(
"'{}' not supported between instances of '{}' and '{}'"
.format(sign, 'Reverse', type(other).__name__)
)
def __lt__(self, other):
self._type_guard('<', other)
return other.value < self.value
def __gt__(self, other):
self._type_guard('>', other)
return other.value > self.value
def __le__(self, other):
self._type_guard('<=', other)
return other.value <= self.value
def __ge__(self, other):
self._type_guard('>=', other)
return other.value >= self.value
def __eq__(self, other):
self._type_guard('==', other)
return other.value == self.value
def __neq__(self, other):
self._type_guard('!=', other)
return other.value != self.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment