Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

boolean

import xml.etree.ElementTree as ET e = ET.Element('Brock',Role="Bodyguard") print bool(e) 

Why is an xml.etree.ElementTree.Element considered False?

I know that I can do if e is not None to check for existence. But I would strongly expect bool(e) to return True.

like image 543
supergra Avatar asked Nov 21 '13 19:11

supergra


People also ask

What is ElementTree?

The cElementTree module is a C implementation of the ElementTree API, optimized for fast parsing and low memory use. On typical documents, cElementTree is 15-20 times faster than the Python version of ElementTree, and uses 2-5 times less memory.

What does Etree parse do?

Parsing from strings and files. lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.


1 Answers

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

like image 74
shx2 Avatar answered Sep 21 '22 10:09

shx2