[python] Comparison feature in Python

Oleg Broytmann phd at phd.russ.ru
Wed Jun 21 08:38:55 EDT 2000


---------- Forwarded message ----------
Date: Wed, 21 Jun 2000 15:33:56 +0400 (MSD)
From: Denis S. Otkidach <den at analyt.chem.msu.ru>
Subject: Re: [python] Comparison feature in Python


Python documentation states that comparison in Python is consistent, but it's
not true. The comparision is performed first by operands types and then by
their ids. The problem is that this statement is true only when both operands
are bult-in. The code listed below demonstrates bug in the builtin comparision
routine. The bug can be easily fixed (at least for instances without __cmp__
method) by changing comparison rules or turned into a feature by documenting
it.


-------------------------------------------------------------------------
#!/usr/bin/env python
"""
This sample code demonstrate that comparison in Python is not consistent
(as documentation say) even when buggy __cmp__ method is not used.
"""
import sys

class B:
    def __repr__(self):
        return "<Object B>"

objects = ['C'*2, B(), 'A'*2]

trash = []

while id(objects[1]) < id(objects[0]):
    trash.append(objects[1])
    objects[1] = B()
while id(objects[2]) < id(objects[1]):
    trash.append(objects[2])
    objects[2] = 'A'*2

print "The source list:", objects # => ['CC', <Object B>, 'AA']

objects.sort()
print objects # => ['CC', <Object B>, 'AA']

objects.reverse()
print objects # => ['AA', <Object B>, 'CC']

objects.sort()
print objects # => [<Object B>, 'AA', 'CC']

# => [<Object B>, 'AA', 'CC'] but one expects ['CC', <Object B>, 'AA']
# as it is after first call of sort method
-------------------------------------------------------------------------

Many thanks to everybody in Python Russian (python-rus) mailing list for
useful discussion.





More information about the Python-list mailing list