Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "if x" and "if x is not None"

Tags:

python

boolean

It appears that "if x" is almost like short-hand for the longer "if x is not None" syntax. Are they functionally identical or are there cases where for a given value of x the two would evaluate differently?

I would assume the behavior should also be identical across Python implementations - but if there are subtle differences it would be great to know.

like image 644
Goyuix Avatar asked Oct 10 '10 16:10

Goyuix


People also ask

How do you know if an object is not None?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

Is vs == for None?

is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.

What does if None do in Python?

The test is designed to check whether or not x was assigned to, or not. When you do if x is None , you call the operator is , which checks the identity of x . None is a singleton in Python and all None values are also the exact same instance. When you say if x , something different happens.

What does not None mean in Python?

It's often used as the default value for optional parameters, as in: def sort(key=None): if key is not None: # do something with the argument else: # argument was omitted. If you only used if key: here, then an argument which evaluated to false would not be considered.


2 Answers

In the following cases:

test = False  test = ""  test = 0 test = 0.0  test = [] test = ()  test = {}  test = set() 

the if test will differ:

if test: #False  if test is not None: #True  

This is the case because is tests for identity, meaning

test is not None 

is equivalent to

id(test) == id(None) #False 

therefore

(test is not None) is (id(test) != id(None)) #True 
like image 97
systempuntoout Avatar answered Sep 22 '22 01:09

systempuntoout


The former tests trueness, whereas the latter tests for identity with None. Lots of values are false, such as False, 0, '', and None, but only None is None.

like image 37
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 01:09

Ignacio Vazquez-Abrams