Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/20129996/why-does-boolxml-etree-elementtree-element-evaluate-to-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...