2
\$\begingroup\$

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?

asked Feb 19, 2015 at 12:33
\$\endgroup\$
2
  • \$\begingroup\$ @ferada: Did you read my question fully? I've already gone over why functools.total_ordering is not adequate by itself . \$\endgroup\$ Commented Feb 19, 2015 at 13:18
  • \$\begingroup\$ Ah, yes, my bad. \$\endgroup\$ Commented Feb 19, 2015 at 13:20

1 Answer 1

3
\$\begingroup\$

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.

answered Feb 19, 2015 at 13:08
\$\endgroup\$
1
  • \$\begingroup\$ Hm. This seems reasonable, but perhaps overcomplicated if this is only being done once. I will consider this method -- thanks! \$\endgroup\$ Commented Feb 19, 2015 at 13:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.