Python 3 __cmp__ semantic change?
Arnaud Delobelle
arnodel at googlemail.com
Sun Nov 23 06:14:23 EST 2008
Arnaud Delobelle <arnodel at googlemail.com> writes:
>> (BTW, I think your earlier decorator had a bug, in that it failed to
>> define __ne__ but then called "self != other".)
>
> That would be true for Python 2.x but I'm explicitly writing code for
> Python 3 here, which, IIRC, infers != correctly when you define ==. I
> can't refer you to the docs because my internet access to some US sites
> seems to be partly broken ATM, but here's a simple example:
>
> Python 3.0rc1+ (py3k:66521, Sep 21 2008, 07:58:29)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class A:
> ... def __init__(self):
> ... self
> ...
>>>>
>>>> class A:
> ... def __init__(self, x):
> ... self.x = x
> ... def __eq__(self, other):
> ... return self.x == other.x
> ...
>>>> a, b, c = A(1), A(1), A(2)
>>>> a==b, b==c, c==a
> (True, False, False)
>>>> a!=b, b!=c, c!=a
> (False, True, True)
>>>>
Getting increasingly frustrated by my inability to reach python.org,
I've compiled the html docs for python 3 in order to find the bit that
explains the behaviour above. But the docs say exactly the opposite:
There are no implied relationships among the comparison
operators. The truth of x==y does not imply that x!=y is
false. Accordingly, when defining __eq__(), one should also define
__ne__() so that the operators will behave as expected. See the
paragraph on __hash__() for some important notes on creating
hashable objects which support custom comparison operations and are
usable as dictionary keys.
So how did I get it into my head that defining __eq__ would create the
correct behaviour for __ne__ automatically? And more puzzlingly, how
come it is what actually happens? Which should I believe: the
documentation or the implementation?
--
Arnaud
More information about the Python-list
mailing list