I currently override the sorting methods provided by namedtuple
by doing something like this:
class Subtitle(namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
def __eq__(self, other): return self.start == other.start
def __ne__(self, other): return self.start != other.start
def __lt__(self, other): return self.start < other.start
def __le__(self, other): return self.start <= other.start
def __gt__(self, other): return self.start > other.start
def __ge__(self, other): return self.start >= other.start
Typically I would use functools.total_ordering
as a decorator to fill in the other sort methods from one, but in this case, collections.namedtuple
already defines sort methods, so decorating with it has no effect.
As it is, fleshing out all of these comparisons when they can be deduced from each other seems a waste of code -- something that is much better handled by functools.total_ordering
if only I could use it. I suppose I could delete the other sort methods from the object, but that seems quite messy. I'm not interested in reimplementing something like functools.total_ordering
from scratch in my code.
Is there a better way to do this?
1 Answer 1
You could use multiple inheritance:
@functools.total_ordering
class SubtitleOrdering(object):
def __eq__(self, other): return self.start == other.start
def __lt__(self, other): return self.start < other.start
class Subtitle(SubtitleOrdering, namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
pass
total_ordering
works normally on SubtitleOrdering
, and making it the first base class overrides the comparison methods of the namedtuple
.
-
\$\begingroup\$ Hm. This seems reasonable, but perhaps overcomplicated if this is only being done once. I will consider this method -- thanks! \$\endgroup\$Chris Down– Chris Down2015年02月19日 13:13:33 +00:00Commented Feb 19, 2015 at 13:13
functools.total_ordering
is not adequate by itself . \$\endgroup\$