Check if xml ElementTree node is None/False [duplicate]

This question already has an answer here:

  • Why does bool(xml.etree.ElementTree.Element) evaluate to False?

    2 answers

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 if check.

Full Code:

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
    print('No UDH!')  # Getting this output

Best answer

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 False or True, or their integer equivalents 0 or 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 __len__() nor __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 None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was 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 None or not None you should use specifically:

if myvar is None: 
elif myvar is not None:

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?

For reference: