[Python-Dev] Python semantic: Is it ok to replace not x == y with x != y? (no)

Victor Stinner victor.stinner at gmail.com
Tue Dec 15 08:11:24 EST 2015


Oh, I sent my email too quickly, I forgot to ask for other operations.

Currently, FAT implements the following optimizations:

* "not (x == y)" replaced with "x != y"
* "not (x != y)" replaced with "x == y"
* "not (x < y)" replaced with "x >= y"
* "not (x <= y)" replaced with "x > y"
* "not (x > y)" replaced with "x <= y"
* "not (x >= y)" replaced with "x < y"
* "not (x in y)" replaced with "x not in y"
* "not (x not in y)" replaced with "x in y"
* "not (x is y)" replaced with "x is not y"
* "not (x is not y)" replaced with "x is y"

I guess that the optimizations on "in" and "is" operators are fine,
but optimizations on all other operations must be removed to not break
the Python semantic.

Python has also some funny objects like math.nan:

>>> math.nan != math.nan
True
>>> math.nan == math.nan
False
>>> math.nan < math.nan
False
>>> math.nan > math.nan
False
>>> math.nan <= math.nan
False
>>> math.nan >= math.nan
False

>>> math.nan != 1.0
True
>>> math.nan == 1.0
False
>>> math.nan <= 1.0
False
>>> math.nan < 1.0
False
>>> math.nan >= 1.0
False
>>> math.nan > 1.0
False

So "not(math.nan < 1.0)" is different than "math.nan >= 1.0"...

Victor

2015-12-15 14:04 GMT+01:00 Victor Stinner <victor.stinner at gmail.com>:
> Hi,
>
> I implemented more constant folding optimizations in my FAT Python
> project, but it looks like I made a subtle change in the Python
> semantic.
>
> Replacing "not x == y" with "x != y" changes the behaviour of Python.
> For example, this optimization breaks test_unittest because
> unittest.mock._Call implements __eq__() but not __ne__().
>
> Is it expected that "not x.__eq__(y)" can be different than
> "x.__ne__(y)"? Is it part of the Python semantic?
>
> IMHO it's a bug in the unittest.mock module, but it's "acceptable"
> because "it just works" :-) So FAT Python must not replace "not x ==
> y" with "x != y" to not break the code.
>
> Should Python emit a warning when __eq__() is implemented but not __ne__()?
>
> Should Python be modified to call "not __eq__()" when __ne__() is not
> implemented?
>
> For me, it can be an annoying and sublte bug, hard to track.
>
> Victor


More information about the Python-Dev mailing list