This question already has an answer here:
Why does bool(xml.etree.ElementTree.Element) evaluate to False?
Is it safe to check whether a variable
myvar has not-None value by simply:
if myvar: print('Not None detected')
I’m asking this because I have a variable and was checking whether the variable was not
None by simply
if variable: but the check has been failing. The variable contains some data but it was evaluating to False in the
from xml.etree import ElementTree as ElementTree root = ElementTree.fromstring('Some xml string') parameters = root.find('Some Tag') udh = parameters.find('UDH') if udh and udh.text: # In this line the check is failing, though the udh variable has value: <Element 'UDH' at 0x7ff614337208> udh = udh.text # Other code else: print('No UDH!') # Getting this output
In Python the boolean (truth) value of the object is not necessarily equal to being
None or not. The correctness of that assumption depends on whether your object has the correct methods defined appropriately. As for Python 2.7:
Called to implement truth value testing and the built-in operation
bool(); should return
True, or their integer equivalents
1. When this method is not defined,
__len__()is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither
__nonzero__(), all its instances are considered true.
Also have a look at the PEP 8, that provides guidance for this issue (emphasis mine):
Comparisons to singletons like
Noneshould always be done with
is not, never the equality operators.
Also, beware of writing
if xwhen you really mean
if x is not None— e.g. when testing whether a variable or argument that defaults to
Nonewas set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
Therefore, to safely test whether you’ve got
not None you should use specifically:
if myvar is None: pass elif myvar is not None: pass
In the case of the
xml.etree.ElementTree.Element the semantics of the boolean evaluation differ from the
None-ness of the object:
- Why does bool(xml.etree.ElementTree.Element) evaluate to False?