Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if <obj> and if <obj> is not None

In writing some XML parsing code, I received the warning:

FutureWarning: The behavior of this method will change in future versions.  Use specific 'len(elem)' or 'elem is not None' test instead.

where I used if <elem>: to check if a value was found for a given element.

Can someone elaborate on the difference between if <obj>: vs if <obj> is not None: and why Python cares which I use?

I almost always use the former because it's shorter and not a double-negative, but often see the latter in other people's source code.

like image 364
Dylan Hettinger Avatar asked Sep 03 '13 02:09

Dylan Hettinger


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).

How do you know if you are None?

Use the is operator to check if a variable is None in Python, e.g. if my_var is None: . The is operator returns True if the values on the left-hand and right-hand sides point to the same object and should be used when checking for singletons like None .

Why is None and not == None?

None is a singleton object (there only ever exists one 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 None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.


1 Answers

if obj is not None test whether the object is not None. if obj tests whether bool(obj) is True.

There are many objects which are not None but for which bool(obj) is False: for instance, an empty list, an empty dict, an empty set, an empty string. . .

Use if obj is not None when you want to test if an object is not None. Use if obj only if you want to test for general "falseness" -- whose definition is object-dependent.

like image 136
BrenBarn Avatar answered Oct 10 '22 19:10

BrenBarn