Bug? If not, how to work around it?

Michele Simionato mis6 at pitt.edu
Fri Aug 8 07:23:48 EDT 2003


bokr at oz.net (Bengt Richter) wrote in message news:<bgv1bf$eoi$0 at 216.39.172.122>...
> Not very tested, but maybe you have to write it something like this:
> 
>  >>> class M(type):
>  ...     def __new__(cls, name, bases, cdict):
>  ...         cdict['__len__'] = lambda self:0
>  ...         return type.__new__(cls, name, bases, cdict)
>  ...
>  >>> class F: __metaclass__ = M
>  ...
>  >>> f=F()
>  >>> F.__len__
>  <unbound method F.<lambda>>
>  >>> F.__len__(f)
>  0
>  >>> len(f)
>  0
> 
>  >>> hasattr(M,'__len__')
>  False
>  >>> hasattr(F,'__len__')
>  True
> 
> Or am I missing the point? ;-/
> 
> Regards,
> Bengt Richter

Yes, you are missing the point, indeed ;)

The point is that if you define a fake special method via __getattr__, it
works if it is called as F.__len___(f), but it DOES not work if it is
called as len(f). I suspect Gonzalo's problem is the same with iter.

Built-in like iter, len, etc. look directly for special methods __iter__,
__len__ etc., *without* checking if they are defined by __getattr__. I
am not saying that this is necessarely a bug, I am saying that this is
not documented and that at least three persons have been beaten by this
issue in the last few months. Not me personally, hence the reason why I didn't
submit a bug report, but this time (if Gonzalo is not going to do that), I
will submit the report, unless Alex is going to prove that this is
already documented ;) 

           Michele




More information about the Python-list mailing list