Message14994
#!/usr/bin/python
"""
Between python1.x and python2.x there has been a major
undocumented (?) change in the behaviour of list.index().
(At least I have been unable to locate the relevant PEP.)
The following snippet illustrates this problem, though
the error
was encountered in a more complex real world situation,
where
a prototype system developed under python1.52 is being
realised
in python2.2.2.
"""
class Order :
def __init__ (self, ordernum) :
self.num = ordernum
def __eq__ (self, other) :
if (hasattr(other, 'num')) :
return self.num == other.num
else :
return self is other
if __name__ == '__main__' :
a = Order(123)
b = Order(234)
c = Order(345)
d = Order(123)
orders = [a, b, c, d]
for o in orders :
print orders.index(o)
"""
Under python1.4 (Solaris 5.6) and python1.52 (Linux
2.4.x) the
output is as would be expected :
0
1
2
3
Under python2.1.1, python2.2.2 and python2.3a2 (all Linux
2.4.x),the output is :
0
1
2
0
From python2.x, list.index() apparently tests for
equivalence
rather than for identity. This is wrong, not the least
because
it breaks existing code (and more importantly, existing
design).
More fundamentally the problem is that it makes
dangerous the
use of the __eq__ hook, to redefine object equivalence,
and contravenes the 'principle of least surprise.'
As far as I know, testing for identity (is) cannot be
overriden,
whereas testing for equivalence (==) can. That being
the case
it is clearly safer to hang list.index() on the fixed
nature of
identity, rather than the redefinable nature of
equivalence.
""" |
|
Date |
User |
Action |
Args |
2007-08-23 14:11:42 | admin | link | issue698561 messages |
2007-08-23 14:11:42 | admin | create | |
|