Strange result ffor object to bool

Peter Otten __peter__ at web.de
Fri Nov 25 04:06:05 EST 2011


ZhouPeng wrote:

> In my program, I get a listen element by
> listen = graphics.find("listen")
> 
> print listen is <Element listen at 6afc20>
> print type listen is <type 'instance'>
> I am sure listen is not None and can be accessed properly.
> 
> But print bool(listen) is False
> if not listen  is True

bool(listen) is False here means that the Element has no children.

Quoting
http://effbot.org/zone/elementtree-13-intro.htm#truth-testing

"""
Truth testing #
The Element type now issues a warning when used in a “boolean context”. To 
get rid of the warning, make the test explicit:
if len(elem):
    ... has at least one children ...

elem = root.find("tag")
if elem is not None:
    ... found ...
Explicit tests work just fine in ET 1.2, of course.
The boolean interpretation will most likely change in future versions, so 
that all elements evaluate to true, also if they have no children.
"""






More information about the Python-list mailing list