[BangPypers] ElementTree object instance evaluates to False?

Vikas BN vikas.bn at gmail.com
Tue Dec 6 05:19:51 CET 2011

Hi All,

   I'm working on a script to parse XML files and am using
cElementTree for the same. However,
   I was under the impression that anything that's a None type or 0 or
"" would evaluate to False
   and the rest would be True (incl an instance of an object).

   That doesn't seem to work with the Element instance. Here's what I get :

>>> import xml.etree.cElementTree as cet
>>> f1 = '/home/vikasn/test.xml'
>>> t1 = cet.parse(f1)
>>>root = t1.getroot()
>>> children = root.getchildren()
>>> len(children)
>>> c1 = children[0]
>>> if c1:
...  print "true"
... else:
...  print "false"
>>> c1
<Element 'name' at 0x2afb45073a50>

    Because of this, I need to resort to clunky stuff like so:

if c1.tag:
  # do something

     To test if my understanding of what evaluates to true/false is
correct or not, I tried the following and seems to be what I expect
would happen.

>>> class Test(object):
...  def __init__(self, num):
...   print num
...   self.num = num
>>> t = Test(1)
>>> t
<__main__.Test object at 0x2afb4507c610>
>>> if t:
...  print "yes"
... else:
...  print "no"

    Anyone else encountered this or even have any insights regarding
this behaviour? I'm using Python2.7.2 on Linux
    if that matters.


More information about the BangPypers mailing list