6

This code:

from lxml.html import fromstring, tostring

s = '<span class="left">Whatever</span>'
e = fromstring(s)
print(tostring(e))
print(bool(e))

outputs:

<span class="left">Whatever</span>
False

Why? How boolean check working in this class? Point me on relevant documentation or code please.

ps
Im using lxml 3.3.5

1
  • If you want to test something not empty: not not "" is False while not not "something" is True
    – daouzli
    Commented Jul 9, 2014 at 18:36

3 Answers 3

7

The relevant place in the Python documentation: https://docs.python.org/2/library/stdtypes.html#truth-value-testing

The ”truthiness” of an object is determined by either the __nonzero__() method or if that does not exist the result of the __len__() method. As your element has no child elements, i.e. its length is 0, it is considered False as a truth value.

4

XML and HTML don't map cleanly to native python data structures. There is no unambiguous method to decide whether an element object should equate to True or False.

If you want to know if you've failed to acquire an element, compare with None. E.g.:

element is None

If you want to know whether your element has any child nodes, use len. E.g.:

len(element) > 0
0

this is what I get with your code ...

>>> print(bool(e))
__main__:1: FutureWarning: The behavior of this method will change in future ve
sions. Use specific 'len(elem)' or 'elem is not None' test instead.
False
>>> e
<Element span at 0x2db85a0>
>>>

seems pretty clear that they overload the __bool__ method and tell you how you should actually check it ...

Not the answer you're looking for? Browse other questions tagged or ask your own question.