elementtree behavior

T

Tim Arnold

I have an XML snippet that I parse with ElementTree, and I get an element
called self.makeToc

Now this code:

print self.makeToc
if self.makeToc != None:
print 'here'
if self.makeToc: print 'but not here'

gives this result:
<Element toc at 40197e88>
here

Clearly self.makeToc has a value, so why isn't "if self.makeToc" True?
That is, if self.makeToc isn't None, why don't I get past 'if self.makeToc'

Can someone point out what am I not understanding?

thanks,
--Tim
 
P

Paul McGuire

Tim Arnold said:
I have an XML snippet that I parse with ElementTree, and I get an element
called self.makeToc

Now this code:

print self.makeToc
if self.makeToc != None:
print 'here'
if self.makeToc: print 'but not here'

gives this result:
<Element toc at 40197e88>
here

Clearly self.makeToc has a value, so why isn't "if self.makeToc" True?
That is, if self.makeToc isn't None, why don't I get past 'if self.makeToc'

Can someone point out what am I not understanding?

thanks,
--Tim
Not sure about your XML Element classes, but a number of Python objects will
evaluate to false even if not set to None:
- boolean with value of 'false'
- integer with value of 0
- list with no elements

Perhaps your Element class evaluates to false if it has no child nodes, or
some similar thing.

-- Paul
 
F

Fredrik Lundh

Tim said:
I have an XML snippet that I parse with ElementTree, and I get an element
called self.makeToc

Now this code:

print self.makeToc
if self.makeToc != None:
print 'here'
if self.makeToc: print 'but not here'

gives this result:
<Element toc at 40197e88>
here

Clearly self.makeToc has a value, so why isn't "if self.makeToc" True?
That is, if self.makeToc isn't None, why don't I get past 'if self.makeToc'

because it's a sequence without any items.

this is discussed in the element overview:

http://effbot.org/zone/element.htm

Note that in ElementTree 1.2 and earlier, the sequence behaviour
means that an element without subelements tests as false (since it's
an empty sequence). To check the return value from a function or
method that may return None instead of a node, you must use an
explicit test.

node = fetchnode()

if not node: # careful!
print "node not found, or node has no subnodes"

if node is None:
print "node not found"

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top