operator overloading - Why do the Python docs say I need to define __ne__ when I define __eq__? -


according python docs: "when defining __eq__(), 1 should define __ne__() operators behave expected".

however, appears python computes __ne__ not __eq__ automatically:

in [8]: class test:     def __eq__(self, other):         print("calling __eq__")    ...:         return isinstance(other, test)    ...:  in [9]: = test()  in [10]: b = test()  in [11]: == b calling __eq__ out[11]: true  in [12]: != b calling __eq__ out[12]: false  in [13]: == 1 calling __eq__ out[13]: false  in [14]: != 1 calling __eq__ out[14]: true 

so what's point of defining __ne__ if it's going return not self.__eq__(other)? , furthermore, behavior documented?

edit

apparently matters using python 3. in python 2, get

in [1]: class test(object):    ...:     def __eq__(self, other):    ...:         print("calling __eq__")    ...:         return isinstance(other, test)    ...:  in [2]: = test()  in [3]: b = test()  in [4]: == b calling __eq__ out[4]: true  in [5]: != b out[5]: true  in [6]: == 1 calling __eq__ out[6]: false  in [7]: != 1 out[7]: true 

but docs referenced python 3 docs. not updated?

python 3 changed behaviour == case, see python 3, what's new:

!= returns opposite of ==, unless == returns notimplemented.

it deemed a useful change.

the fact documentation has not been updated indeed long standing bug.

however, comment on report points out, if inherit class has defined __ne__, overriding __eq__ not enough , you'll have override __ne__ method.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -