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.
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).
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With