From f64b487b89085f8553e8875ce54c1783c618ee9d Mon Sep 17 00:00:00 2001 From: Dylan Baker Date: Thu, 22 Dec 2016 15:06:13 -0800 Subject: db/message: replace __cmp__ with rich comparisons This replaces the deprecated __cmp__ function with the more modern __lt__, __eq__, and __ne__, and then uses functools.total_ordering to implemented the remaining pieces of the rich comparison protocol automatically. It also make use of the NotImplemented singleton, which python uses to signal to rich comparators that this class doesn't no how to compare to the other class, which results in the complementary method from the other class being used, and if both return NotImplemented than a TypeError is generated. There are two reasons to make this change. First, python 3 only supports rich comparisons, and second rich comparisons are much faster than using cmp (and the __cmp__ protocol) because cmp is called at least 3 times per element, while a rich comparitor is called one per element. functools.total_ordering is in the standard library from 2.7 and 3.3, and will implement the rich comparison protocol provided that __eq__ and at least one of __lt__, __le__, __ge__, or __gt__ are implemented. It does not (oddly enough) implement __ne__, so I've implemented that manually. --- alot/db/message.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'alot') diff --git a/alot/db/message.py b/alot/db/message.py index 5566fa64..2f5e61e3 100644 --- a/alot/db/message.py +++ b/alot/db/message.py @@ -3,6 +3,7 @@ # For further details see the COPYING file import email import email.charset as charset +import functools from datetime import datetime from notmuch import NullPointerError @@ -16,6 +17,7 @@ from ..settings import settings charset.add_charset('utf-8', charset.QP, charset.QP, 'utf-8') +@functools.total_ordering class Message(object): """ @@ -60,10 +62,20 @@ class Message(object): """needed for sets of Messages""" return hash(self._id) - def __cmp__(self, other): - """needed for Message comparison""" - res = cmp(self.get_message_id(), other.get_message_id()) - return res + def __eq__(self, other): + if isinstance(other, type(self)): + return self.get_message_id() == other.get_message_id() + return NotImplemented + + def __ne__(self, other): + if isinstance(other, type(self)): + return self.get_message_id() != other.get_message_id() + return NotImplemented + + def __lt__(self, other): + if isinstance(other, type(self)): + return self.get_message_id() < other.get_message_id() + return NotImplemented def get_email(self): """returns :class:`email.Message` for this message""" -- cgit v1.2.3