Title: invalid conversion xml.etree.ElementTree.Element object to boolean
Type: Stage:
Components: XML Versions: Python 2.5
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mishok13, pitrou, xaka
Priority: normal Keywords:

Created on 2008-06-25 09:09 by xaka, last changed 2008-06-25 12:27 by benjamin.peterson. This issue is now closed.

Messages (3)
msg68720 - (view) Author: Pavel Strashkin (xaka) Date: 2008-06-25 09:09
Python 2.5.2 (r252:60911, May  7 2008, 15:19:09)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.etree.ElementTree import Element
>>> e = Element('Test', {'attr' : 'value'})
>>> b = not e
>>> print b

Why i'm getting True here instead of False?
Because of this i can not do:
if not e:
    # here some logic
msg68721 - (view) Author: Andrii V. Mishkovskyi (mishok13) Date: 2008-06-25 09:30
To quote Python Library Reference, paragraph 3.1:
"""Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below. The following
values are considered false: 
 - instances of user-defined classes, if the class defines a
__nonzero__() or __len__() method, when that method returns the integer
zero or bool value False.
And back to python console:
In [112]: from xml.etree.ElementTree import Element

In [113]: e = Element('foo', {'key': 'value'})

In [114]: len(e)
Out[114]: 0

In [115]: not e
Out[115]: True

This is because Element is just a container and acts more like a list.
So, if you actually append items to this list-like structure, you'll get

In [116]: e.append(Element('bar', {42: 1337}))

In [117]: e.append(Element('baz', {'whatever': 'wherever'}))

In [118]: len(e)
Out[118]: 2

In [119]: not e
Out[119]: False

In conclusion, this just doesn't look like a bug to me. You could try
using "if e is not None" form.
msg68723 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2008-06-25 10:22
Indeed, this is not a bug, although it can be misleading.
Generally, if you test for None, it is better to write "if x is None",
it is at the same time more accurate, more explicit for someone reading
your code, and also executes faster than "if not x".
Date User Action Args
2008-06-25 12:27:49benjamin.petersonsetstatus: open -> closed
resolution: not a bug
2008-06-25 10:22:58pitrousetnosy: + pitrou
messages: + msg68723
2008-06-25 09:30:01mishok13setnosy: + mishok13
messages: + msg68721
2008-06-25 09:09:15xakacreate