Is there a significant difference between: if not a == 'bar' and if a = = bar?

Are these just two ways to write the same code? Is there any functional difference that I should know about?

>>> a = 'foo' >>> if not a == 'bar': ... 'its not' ... 'its not' >>> if a != 'bar': ... 'its not' ... 'its not' 
+4
source share
2 answers

In python, to check whether an object equal or not equal to another object is equal or not, special functions are called. __eq__ is called for verification == , and __ne__ is called for verification !=

In general, an object can define __ne__ differently than __eq__ .

eg.

 class Junk(object): def __ne__(self, other): return False def __eq__(self, other): return False j = Junk() print not j == 1 print j != 1 

This gives:

 True False 

However, this would be especially vicious. Usually you will never have to worry about this.

+6
source

not a == b translates to a call not a.__eq__(b) , and a != b translates to a call a.__ne__(b) . For the most part (almost every normal object I can think of), __ne__ is defined as def __ne__(self, other): not self.__eq__(other) , so there is no functional difference. However, you can easily create a psychotic object that would be equal and not equal to other values ​​by simply overriding __ne__ right way (although I can't come up with a case where it makes sense right now).

Inline objects, on the other hand, are likely to implement a != b in a way that is slightly faster than not a == b , but probably there can be no noticeable amount.

+1
source

Source: https://habr.com/ru/post/1386438/


All Articles