elementtree behavior

Fredrik Lundh fredrik at pythonware.com
Mon Sep 27 16:41:04 EDT 2004


Tim Arnold wrote:

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






More information about the Python-list mailing list