Interesting list() un-optimization

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 11 00:35:50 CET 2013


On Sun, 10 Mar 2013 18:34:58 -0400, Roy Smith wrote:

> Yeah, that's what I was afraid of.  The "obvious" solution of:
> 
> class QuerySet(mongoengine.queryset.QuerySet):
>     def __init__(self, document, collection):
>         super(QuerySet, self).__init__(document, collection) [...]
>         del self.__len__
> 
> results in:
> 
> [rest of stack dump elided]
>     del self.__len__
> AttributeError: __len__
> 
> which I don't understand.

You don't define a per-instance custom QuerySet attribute called __len__, 
so you can't delete it from the instance.

The existing __len__ attribute is attached to the mongoengine 
queryset.QuerySet class, not the instance. You could monkeypatch the 
parent class, but that will probably break something else:

    del mongoengine.queryset.QuerySet.__len__


or you could try over-riding __len__ with a fake that pretends it doesn't 
exist:


def __len__(self):
    raise AttributeError


Try that and see it it works. (It may not.)


-- 
Steven



More information about the Python-list mailing list