iter jitters
Steven Brent
stevenbee at removethis.part.att.net
Tue May 4 17:33:04 EDT 2004
OK, thanks ... that explains why my other idea of returning a new list
to iterate over didn't work either. Talk about chasing one's tail...
Btw, I just realized that a custom __getitem__ method I defined earlier
in the module(and unhelpfully didnt post), handles the iteration in 2 lines!
def __getitem__(self, index):
return self.data[index]
This is the kind of thing I was after, because I didn't want any
iteration going on in the __iter__ definition itself. Trying to reinvent
the wheel for exercise.
But generators are cool, and I promise to use them lots :-)
This seems to be a recurring pattern for me; I get deep into confusion
by skipping over the obvious. Thanks for the clarity and knowledge.
--Steven the newbie
===========================
Diez B. Roggisch wrote:
> 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
>
>
>
More information about the Python-list
mailing list