[英]Python XML 'TypeError: must be xml.etree.ElementTree.Element, not str'
[英]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)
为什么xml.etree.ElementTree.Element
被视为False
?
我知道if e is not None
,我可以做if e is not None
以检查是否存在。 但我强烈期望bool(e)
返回True
。
事实证明,如果Element
对象没有子Element
则它们被视为False
值。
我在源头发现了这个:
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
即使内联评论也同意你的观点 - 这种行为是不确定的;)
来自文档:
http://docs.python.org/library/xml.etree.elementtree.html#element-objects
警告:没有子元素的元素将测试为False。 此行为将在以后的版本中更改。 使用特定的len(elem)或elem是None测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.