Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my IDE suggest to rewrite != 0 to is not 0

Tags:

python

pycharm

My python IDE PyCharm by defaults suggests to change the following line of python:

if variable != 0:

to

if variable is not 0:

Why does it suggest this? Does it matter at all for the execution (i.e. does this behave different for any edge cases)?

like image 483
Peter Smit Avatar asked Dec 10 '25 13:12

Peter Smit


2 Answers

It's a bug. You should not test integers by identity. Although it may work ok for small integers, it's just an implementation detail.

If you were checking variable is False, that would be ok. Perhaps the IDE is tripped up by the semantics

like image 164
John La Rooy Avatar answered Dec 13 '25 01:12

John La Rooy


The != operator checks for non equality of value. The is operator is used to check for identity. In Python, you cannot have two instances of the same integer literal so the expressions have the same effect. The is not 0 reads more like English which is probably why the IDE is suggesting it (although I wouldn't accept the recommendation).

I did try some analysis. I dumped the bytecode for both the expressions and can't see any difference in the opcodes. One has COMPARE_OP 3 (!=) and the other has COMPARE_OP 9 (is not). They're the same. I then tried some performance runs and found that time taken is negligibly higher for the !=.

like image 43
Noufal Ibrahim Avatar answered Dec 13 '25 01:12

Noufal Ibrahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!