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

匿名 (未验证) 提交于 2019-12-03 01:59:02

问题:

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.

回答1:

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



回答2:

From the docs:

http://docs.python.org/2/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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!