iter jitters

Diez B. Roggisch deetsNOSPAM at web.de
Tue May 4 16:57:07 EDT 2004


Steven Brent wrote:

> In the snippet below, I'm trying to overload the __iter__ list method:
> 
>      def __iter__(self):
>              print "using custom iter"
>              counter = 0
>              end = len(self.data) - 1
>              while counter <= end:
>                 print self.data[counter]
>                 counter += 1
> 
> It pretty much works, except that the output is ugly when the while loop
> falls off the end of the list:
> 

>        File "mylist.py", line 38, in ?
>          for item in L3:print item,
>      TypeError: iter() returned non-iterator of type 'NoneType'
> 
> Oh, yeah, plus it's adding a newline at the end of each item even though
> I've got the comma there. I'm gonna keep plugging away to see if I can
> figure this out, but stuff like this makes me frustrated... Thanks a
> million.

I think you've got something wrong here - __iter__ is supposed to return an
object that supports the iteration protocol - mainly a next() method that
throws an exception when no more elements are available.

Today, this kind of thingy is usually done using generators:

class foo:
    def __init__(self):
        self.data = range(10)
        
    def __iter__(self):
        def _my_iter():
            for e in self.data:
                yield e
        return _my_iter()


for i in foo():
    print i
    


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list