Comparison feature in Python 
Author Message
 Comparison feature in Python

Quote:
---------- Forwarded message ----------
Date: Wed, 21 Jun 2000 15:33:56 +0400 (MSD)

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.



Sun, 08 Dec 2002 03:00:00 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. Speed comparison: Python-Perl-Java-Smalltalk

2. Smalltalk and Python - a Comparison

3. Comparison of Lisp to Python

4. C, C++, Java, Perl, Python, Rexx, Tcl comparison

5. Python and Ruby: a comparison

6. Python and Ruby: a comparison

7. REPOST: Re: Python and Ruby: a comparison

8. Help: Rich comparison in derived class, but not in base (boost.python)

9. Python / Visual Basic mathematical comparison

10. Python Parsers Comparison

11. Python tutorial/comparison for C++ programmer

12. Yet another language comparison: Pliant and Python

 

 
Powered by phpBB® Forum Software