[Chandler-dev] Harmful usage of len()

Andi Vajda vajda at osafoundation.org
Wed Jun 6 10:54:07 PDT 2007


On Wed, 6 Jun 2007, D John Anderson wrote:

> Is it ever the case that __nonzero__ would return a value inconstant from 
> using __len__ so using it instead of len would cause a bug?

Not in the Collection class. __nonzero__() is more efficient than __len__() in 
determining if a collection is empty or not. For instance, If the collection 
has no index on it, __len__() will iterate the entire collection to count its 
items whereas __nonzero__() will only iterate to the first item - this is 
enough to determine if the collection is empty or not. On the other hand, if 
the collection has an index, __nonzero__() and __len__() are equivalent since 
an index knows its length at all times and no iteration is needed to determine 
it.

>> Also, doing a len() on some objects causes side effects to happen that
>> you may not want, like creating repository indexes (of course avoiding
>> index creation in one spot will likely just move it to another spot
>> which you may not want).

I should point out that this is not a repository feature but a feature of 
John's code. The repository never creates indexes on its own initiative.
(see line 1012 of parcels/osaf/pim/collections.py)

Andi..



More information about the chandler-dev mailing list