Missing __len__() in ResultSet

Asked by Henning Eggers

Is the fact that the __len__() method is missing from ResultSet a design choice or a bug? It could be easily implemented using count(), couldn't it?

Question information

English Edit question
Storm Edit question
No assignee Edit question
Solved by:
James Henstridge
Last query:
Last reply:
Revision history for this message
Best James Henstridge (jamesh) said :

The lack of __len__() is a design choice.

Various parts of Python assume that __len__() is a cheap operation. For example, when building a list with list(iterator), the list constructor will call the __len__() method on the iterator (if it exists) to preallocate the list before retrieving the values from the iterator.

So if ResultSet had a __len__ method, converting a result set to a list would result in two database queries rather than one. There are a few other places that will implicitly call __len__(), such as treating the object as a boolean value.

Given the expense of the query, it makes sense to avoid having it issued implicitly.

Revision history for this message
Henning Eggers (henninge) said :

Thanks for taking the time to explain!

Revision history for this message
Henning Eggers (henninge) said :

You should create an FAQ from this, as the explanation is valid generally and the question might arise again. I'd do it myself but I guess since this is not part of the Launchpad project, I lack the right to do so.


Revision history for this message
James Henstridge (jamesh) said :

For what it is worth, we added a __len__() method to result sets in the SQLObject fork that Launchpad used to run on. I think I did up the patch to remove it again due to the issues outlined above.