[Python-checkins] cpython (2.7): Update the sorting howto to reflect the PEP 8 advisory to define all six rich
raymond.hettinger
python-checkins at python.org
Tue Jan 10 08:55:32 CET 2012
http://hg.python.org/cpython/rev/11a8a6c8cdd9
changeset: 74319:11a8a6c8cdd9
branch: 2.7
user: Raymond Hettinger <python at rcn.com>
date: Tue Jan 10 07:55:17 2012 +0000
summary:
Update the sorting howto to reflect the PEP 8 advisory to define all six rich comparisons.
files:
Doc/howto/sorting.rst | 10 +++++++---
1 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/Doc/howto/sorting.rst b/Doc/howto/sorting.rst
--- a/Doc/howto/sorting.rst
+++ b/Doc/howto/sorting.rst
@@ -276,11 +276,15 @@
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> assert sorted(data, reverse=True) == list(reversed(sorted(reversed(data))))
-* The sort routines are guaranteed to use :meth:`__lt__` when making comparisons
- between two objects. So, it is easy to add a standard sort order to a class by
- defining an :meth:`__lt__` method::
+* To create a standard sort order for a class, just add the appropriate rich
+ comparison methods:
+ >>> Student.__eq__ = lambda self, other: self.age == other.age
+ >>> Student.__ne__ = lambda self, other: self.age != other.age
>>> Student.__lt__ = lambda self, other: self.age < other.age
+ >>> Student.__le__ = lambda self, other: self.age <= other.age
+ >>> Student.__gt__ = lambda self, other: self.age > other.age
+ >>> Student.__ge__ = lambda self, other: self.age >= other.age
>>> sorted(student_objects)
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
--
Repository URL: http://hg.python.org/cpython
More information about the Python-checkins
mailing list