Strange result ffor object to bool

ZhouPeng zpengxen at gmail.com
Fri Nov 25 05:09:43 EST 2011


Thanks all.

I am a c/c++ programer before,
So I directly think it is the same roughly between

if not obj: (in python) and if (!obj) {(in c/c++)

/ if obj: (in python) and if (obj) {(in c/c++)

That if obj is not None, 'if obj:' goes true branch, 'if not obj:'
goes false branch,
and I don't need to care where the obj is from (what type or what lib)

But, Now it seem not be consistent, so I feel strange.
And it seem be obj's library related in python.

On Fri, Nov 25, 2011 at 4:59 PM, Peter Otten <__peter__ at web.de> wrote:
>What is a listen element? It is not a standard Python object. What
>library is it from?
from xml.etree.ElementTree

On Fri, Nov 25, 2011 at 5:06 PM, Peter Otten <__peter__ at web.de> wrote:
> 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
Thanks,
> """
> 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.
> """
Yea,  you are right.
And I got it later, when I run my program in python 2.7.2,
It complains:
FutureWarning: The behavior of this method will change in future versions.
Use specific 'len(elem)' or 'elem is not None' test instead. if not graphics:
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
Zhou Peng



More information about the Python-list mailing list