Augmented generators?

Paul Rubin http
Tue Jan 10 14:03:39 EST 2006


"Andrew Koenig" <ark at acm.org> writes:
> Can anyone think of an easy technique for creating an object that acts like 
> a generator but has additional methods?

> For example, it might be nice to be able to iterate through an associative 
> container without having to index it for each element.  

Normally you'd define a class and give it __iter__ and next operations.
I guess that can get messy.  Does it qualify as easy for your purposes?

> Of course I can write such a beast as a class, but that prevents me from 
> taking advantage of the yield statement in its implementation.

You can make an internal function that's a generator with a yield
statement (or a generator expression instead of a function, if simple
enough).  The class's 'next' method would loop through the generator
and return each value from it.

Let me try your example:

class kviter:
   def __init__(self, d):
      self.d = d
   def __iter__(self):
      def iter1(d, s=self):
         for k in d:
            # lambda not really needed here, but you wanted value to
            # be callable instead of just an attribute
            s.value = (lambda r=d[k]: r)
            yield k
      return iter1(self.d)

a = {1:5,2:6,3:7}
it = kviter(a)
for b in it:
    print b, it.value()


>>> ## working on region in file /usr/tmp/python-15915wBw...
1 5
2 6
3 7



More information about the Python-list mailing list