[lxml-dev] .find() evals to false

Martijn Faassen faassen at infrae.com
Thu Aug 4 15:27:25 CDT 2005


dharana wrote:
> Martijn Faassen wrote:
> 
>> dharana wrote:
[snip]
>>> I've been hit by this several times by now. I think that an element 
>>> like a node shouldn't eval to false. What do you think about this? 
>>
>> Hm, could you test what it does with the equivalent operation in
>> ElementTree? I want to stay compatible with that.
 >
> I'm in the middle of a release, I don't have Celement installed, I will 
> check it after this, sorry.
> 
> In any case, the current behaviour sounds really ilogical to me.

I just tested it with ElementTree, and the behavior is the same as in 
lxml; I added a test for it. I won't be changing the behavior for 
compatibility reasons.

What happens is that an element evaluates to False if it has no 
children, and True if it does. The presence of text content, attributes 
or a tail does not affect the boolean status; if no elements exist it'll 
still be False.

find() has the behavior to return None if the value cannot be found. You 
can change your tests to something like:

if xmldoc.find('child') is not None:
     ...

to check whether you have a child.

Note that you could also be using xpath(), which in lxml is typically 
faster than find() (besides it being more powerful). xpath() will always 
return a list, though it may be an empty one.

Regards,

Martijn



More information about the lxml mailing list