Ninja420
Ninja420

Reputation: 3872

Difference between 'not x' and 'x==None' in 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 ?

Upvotes: 10

Views: 3324

Answers (5)

Edward Falk
Edward Falk

Reputation: 10063

not x is true for a wide variety of values, e.g. 0, None, "", False, [], {}, etc.

x == None is only true for the one specific value None.

If x is a class instance, then both not x and x == None will be false, but that doesn't mean that those are equivalent expressions.


Fine; that previous paragraph should read:

If x is a class instance, then both not x and x == None will be false unless someone is playing silly buggers with the class definition.

Upvotes: -1

Bleeding Fingers
Bleeding Fingers

Reputation: 7129

If x is positive the not of it means negative and vice-versa.

x == None means it will only be True if x is None is True else False. Check this.

By positive I mean the if block is chosen. True is also positive.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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

Upvotes: 5

zmo
zmo

Reputation: 24812

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.

Upvotes: 13

Ry-
Ry-

Reputation: 224913

Yes; not uses __bool__ (in Python 3; Python 2 uses __nonzero__), and x == None can be overridden by __eq__.

(Both are shown here.)

Upvotes: 2

Related Questions