Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'not x' and 'x==None' in python

Tags:

python

Can not x and x==None give different answers if x is a class instance ?

I mean how is not x evaluated if x is a class instance ?

like image 398
Ninja420 Avatar asked Jun 22 '13 16:06

Ninja420


2 Answers

yes it can give different answers.

x == None

will call the __eq__() method to valuate the operator and give the result implemented compared to the None singleton.

not x

will call the __nonzero__() (__bool__() in python3) method to valuate the operator. The interpreter will convert x to a boolean (bool(x)) using the mentioned method and then inverse its returned value because of the not operator.

x is None

means that the reference x points to the None object, which is a singleton of type NoneType and will valuate false in comparaisons. The is operator tests object identity, and thus whether or not the two objects compared are the same instance of an object, and not similar objects.

like image 72
zmo Avatar answered Oct 17 '22 09:10

zmo


class A():
    def __eq__(self, other):  #other receives the value None
        print 'inside eq'
        return True
    def __nonzero__(self):    
        print 'inside nonzero'
        return True
...     
>>> x = A()
>>> x == None      #calls __eq__
inside eq
True
>>> not x          #calls __nonzero__
inside nonzero
False

not x is eqivalent to:

not bool(x)

Py 3.x:

>>> class A(object):
        def __eq__(self, other):    #other receives the value None
                print ('inside eq')
                return True
        def __bool__(self):    
                print ('inside bool')
                return True
...     
>>> x = A()
>>> x == None       #calls __eq__
inside eq
True
>>> not x           #calls __bool__ 
inside bool 
False
like image 30
Ashwini Chaudhary Avatar answered Oct 17 '22 09:10

Ashwini Chaudhary