Inconsistency in Python's Comparisons

Dietrich Epp dietrich at zdome.net
Tue Mar 16 19:21:58 EST 2004


Without invoking double-underscore black magic, it is possible to 
choose a, b, and c in Python such that:

a < b
b < c
c < a

This could cause sorting functions to malfunction.

 >>> class t(object):
...     pass
...
 >>> a = t()
 >>> b = u'0'
 >>> c = '1'
 >>> a < b
True
 >>> b < c
True
 >>> c < a
True

Possible kludge fix: Change default_3way_compare() to use "basestring" 
as the typename for both built-in string types.

Possible elegant fix: Any class whose members may either be less than 
or greater than members of a different class, which often share a 
common superclass, use the name of the superclass for comparisons with 
objects of incompatible types.  This parallels the comparison of 
numeric types because they compare as if their type name were empty.





More information about the Python-list mailing list