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

前端 未结 2 752
遥遥无期
遥遥无期 2020-12-15 03:35
import xml.etree.ElementTree as ET
e = ET.Element(\'Brock\',Role=\"Bodyguard\")
print bool(e)

Why is an xml.etree.ElementTree.Element

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 04:25

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

提交回复
热议问题