Issue 3195: invalid conversion xml.etree.ElementTree.Element object to boolean (original) (raw)
Issue3195
Created on 2008-06-25 09:09 by xaka, last changed 2022-04-11 14:56 by admin. 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 True Why i'm getting True here instead of False? Because of this i can not do: if not e: # here some logic pass | ||
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: [skipped] - 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 this: 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) * ![]() |
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". |
History | |||
---|---|---|---|
Date | User | Action | Args |
2022-04-11 14:56:35 | admin | set | github: 47445 |
2008-06-25 12:27:49 | benjamin.peterson | set | status: open -> closedresolution: not a bug |
2008-06-25 10:22:58 | pitrou | set | nosy: + pitroumessages: + |
2008-06-25 09:30:01 | mishok13 | set | nosy: + mishok13messages: + |
2008-06-25 09:09:15 | xaka | create |