检查xml ElementTree节点是否为None/False

Sha*_*iul 7 python

myvar通过简单地检查变量是否具有非 - 无值值是否安全:

if myvar:
    print('Not None detected')
Run Code Online (Sandbox Code Playgroud)

我问这个是因为我有一个变量并且正在检查变量是否不是None简单if variable:但是检查失败了.该变量包含一些数据,但在if检查中评估为False .

完整代码:

from xml.etree import ElementTree as ElementTree

root = ElementTree.fromstring('Some xml string')

parameters = root.find('Some Tag')

udh = parameters.find('UDH')

if udh and udh.text:  # In this line the check is failing, though the udh variable has value: <Element 'UDH' at 0x7ff614337208>
    udh = udh.text
    # Other code
else:
    print('No UDH!')  # Getting this output
Run Code Online (Sandbox Code Playgroud)

moo*_*eep 6

在Python中,对象的布尔(真值)值不一定等于None或不等于.该假设的正确性取决于您的对象是否正确定义了正确的方法.至于Python 2.7:

object.__nonzero__(self)

被称为实施真值测试和内置操作bool(); 应该返回FalseTrue,或它们的整数等价物01.如果未定义此方法,__len__()则调用此方法(如果已定义),如果其结果为非零,则将该对象视为true.如果一个类既未定义也__len__()未定义__nonzero__(),则其所有实例都被视为真.

另请参阅PEP 8,它为此问题提供了指导(强调我的):

与单身人士的比较None应始终使用is或者is not从不使用相等运算符.

此外,if x当你真正想要时要小心写作if x is not None- 例如,在测试默认的变量或参数是否None设置为其他值时.另一个值可能有一个类型(如容器)在布尔上下文中可能为false!

因此,要安全地测试您是否已经None或者not None您应该具体使用:

if myvar is None: 
    pass
elif myvar is not None:
    pass
Run Code Online (Sandbox Code Playgroud)

xml.etree.ElementTree.Element布尔评估的语义不同于None对象的-ness的情况下:

以供参考:

  • [pep 8](http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations)对此也有一句话:*另外,当你真的要小心写``if x``意思是``如果x不是无'`* (3认同)