[Erp5-dev] Why are some class instances false?

Yoshinori Okuji yo at nexedi.com
Wed May 19 13:03:08 CEST 2004


In ERP5, sometimes class instances (such as a Folder) can be false, if 
you do this:

obj = kwargs['context']
if obj:
  blah blah


Short answer:
If obj has no subobjects, it is false. Do not use this test but use "obj 
is not None".


Long answer:

Python checks if an object is false or true in this way:

1. If it is None, false.
2. If it has the attribute __int__, call int(obj). If this result is 
zero, false.
3. If it has the attribute __len__, call len(obj). If this result is 
zero, false.
4. Otherwise, true.

Note that if an object is an instance of BTreeFolder2 or a subclass of 
it, the object has __len__. In this case, if this object has no 
content, this object is false.

So it is always better to use more explicit comparison tests, like 
these:

if obj is not None:
  blah
if obj == 0:
  blah
if len(obj) == 0:
  blah

YO
-- 
Yoshinori Okuji, Nexedi Research Director
Nexedi: Consulting and Development of Free / Open Source Software
http://www.nexedi.com
ERP5: Free / Open Source ERP Software for small and medium companies
http://www.erp5.org
Storever: OpenBrick, WiFi infrastructure, notebooks and servers
http://www.storever.com




More information about the Erp5-dev mailing list