Bug? If not, how to work around it?

Mark Day mday at apple.com
Wed Aug 6 23:58:02 CEST 2003


In article <u8m2jvsus3om8r96ggnej9s7u3iecv3e29 at 4ax.com>, Gonçalo
Rodrigues <op73418 at mail.telepac.pt> wrote:

> >>> class Test(object):
> ...    def __init__(self, obj):
> ...       self.__obj = obj
> ...    def __getattr__(self, name):
> ...       return getattr(self.__obj, name)
> ...    
> 
> Now:
> 
> >>> a = Test([])
> >>> a.__iter__
> <method-wrapper object at 0x0112CF30>
> >>> iter(a)
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: iteration over non-sequence
> >>> 
> 
> Is this a bug? If not, how to code Test such that iter sees the
> __iter__ of the underlying object?

I'm guessing that iter() is looking for an __iter__ attribute without
going through __getattr__ to find it.  So, I tried adding the following
method to the Test class:

    def __iter__(self):
        return self.__obj.__iter__

but that returned the following error:

TypeError: iter() returned non-iterator of type 'method-wrapper'

I changed the __iter__ method to the following, and it seems to do what
you want:

    def __iter__(self):
        return iter(self.__obj)

As to whether this is a bug, I don't know.

-Mark




More information about the Python-list mailing list