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

As it turns out, Element objects are considered a False value if they have no children.

I found this in the source:

def __nonzero__(self):
    warnings.warn(
        "The behavior of this method will change in future versions.  "
        "Use specific 'len(elem)' or 'elem is not None' test instead.",
        FutureWarning, stacklevel=2
        )
    return len(self._children) != 0 # emulate old behaviour, for now

Even the inline comment agrees with you -- this behavior is iffy ;)


From the docs:

http://docs.python.org/library/xml.etree.elementtree.html#element-objects

Caution: Elements with no subelements will test as False. This behavior will change in future versions. Use specific len(elem) or elem is None test instead.

Tags:

Python

Boolean