Iteratoration question

Robert Kern robert.kern at gmail.com
Fri Apr 3 01:18:02 CEST 2009


On 2009-04-02 18:08, andrew cooke wrote:
> grocery_stocker wrote:
>>> in summary: iterator is bound to one instance of "it", while some_func()
>>> returns a new instance each time it is called.
>>>
>>> BUT
>>>
>>> while what you are doing is interesting, it is not the same as Python's
>>> iterators, which use "yield" from a function and don't require storing a
>>> value in a class.  look for "yield" in the python docs.  this comment
>>> may
>>> be irrelevant; i am just worried you are confusing the above (which
>>> apart
>>> from the mistake about instances is perfectly ok) and python's iterators
>>> (which use next(), yield, etc).
>>>
>> Okay, one last question for now
>>
>> When I have the follow class
>>
>>>>> class it:
>> ...    def __init__(self):
>> ...        self.count = -1
>> ...    def next(self):
>> ...        self.count +=1
>> ...        if self.count<  4:
>> ...            return self.count
>> ...        else:
>> ...            raise StopIteraton
>> ...
>>
>>
>>
>>>>> value = it()
>> How comes I can;t go over 'value' like in the following
>>
>>>>> for x in value:
>> ...     print x
>> ...
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in ?
>> TypeError: iteration over non-sequence
>>
>> But yet, I can do...
>>
>>>>> value.next()
>> 0
>>>>> value.next()
>> 1
>>>>> value.next()
>> 2
>>>>> value.next()
>> 3
>
> replace return with yield and it might work.
>
> i have to go eat, but if it doesn't read the python docs on iterators -
> for example http://docs.python.org/reference/expressions.html#index-1825

No, .next() needs to be a regular function that returns a value. What he needs 
is an __iter__() method that returns self. Alternately, __iter__ could be a 
generator, and you wouldn't implement a .next() at all.

In [1]: class it(object):
    ...:     def __init__(self):
    ...:         self.count = -1
    ...:     def __iter__(self):
    ...:         return self
    ...:     def next(self):
    ...:         self.count += 1
    ...:         if self.count < 4:
    ...:             return self.count
    ...:         else:
    ...:             raise StopIteration
    ...:
    ...:

In [2]: class it2(object):
    ...:     def __init__(self):
    ...:         self.count = -1
    ...:     def __iter__(self):
    ...:         self.count += 1
    ...:         while self.count < 4:
    ...:             yield self.count
    ...:             self.count += 1
    ...:
    ...:

In [3]: list(it())
Out[3]: [0, 1, 2, 3]

In [4]: list(it2())
Out[4]: [0, 1, 2, 3]


-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list