Interesting list() un-optimization
Roy Smith
roy at panix.com
Sun Mar 10 19:50:22 EDT 2013
In article <513d18d6$0$6512$c3e8da3$5496439d at news.astraweb.com>,
Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> 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.)
Yeah, that was one of the things I experimented with. It seems to work,
but like most of these other things, I suspect it's version specific.
If list() does:
try:
l = obj.__len__()
except AttributeErrror:
l = 0
then we're good. On the other hand, if it does:
if obj.getattr('__len__', None):
# etc
then it fails.
At this point, I'm thinking the monkeypatch is the right solution.
More information about the Python-list
mailing list