Rich Comparisons

Prior to Python 2.1

  • Comparison of objects handled through a special __cmp__(self,other) method.
  • Returns negative if self < other, 0 if self == other, positive if self > other

Python 2.1

  • Each comparison operator can be defined individually (<, <=, >, >=, ==, !=)
  • __lt__(), __le__(), __gt__(), __ge__(), __eq__(), and __ne__() special methods
  • Methods can return any value, raise exceptions, etc.

Primary applications

  • Comparison of types for which only a subset of operators make sense.
  • Example: complex numbers. Can test for equality, but < and > mathematically meaningless.
  • Matrices and vectors. May want to compute comparison of individual elements.
<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 24
July 26, 2001, beazley@cs.uchicago.edu
>>>