More baby squeaking - iterators in a class

Terry Reedy tjreedy at udel.edu
Thu Dec 30 15:01:51 EST 2004


"Bulba!" <bulba at bulba.com> wrote in message 
news:njf8t09i9injk8cr7r1858ng4gkq6fu5o6 at 4ax.com...
> "Define a __iter__() method which returns an object with a next()
> method. If the class defines next(), then __iter__() can just return
> self:"
>
> The thing is, I tried to define __iter__() directly without explicit
> defining next (after all, the conclusion from this passage should
> be that it's possible).

It is, see below.

> class R:
> def __init__(self, d):
> self.d=d
> self.i=len(d)
> def __iter__(self):
> if self.i == 0:
> raise StopIteration
> self.i -= 1
> return self.d[self.i]

Change 'return' to 'yield'.  Then r.__iter__() *will* return a 
(generator)iterator with a .next method, as required.  But it will only 
yield one value before running off the end.  Since __iter__ is meant to be 
called only once, you need to loop explicitly in the generator.  For 
instance

  def __iter__(self):
    i,d = self.i, self.d
    while i
      i =- 1
      yield d[i]

Copying i makes the generator non-destuctive.

(PS, use spaces, not tabs, in posted code.)

Terry J. Reedy






More information about the Python-list mailing list