Augmented generators?

Bengt Richter bokr at oz.net
Tue Jan 10 21:54:44 CET 2006


On Tue, 10 Jan 2006 18:37:13 GMT, "Andrew Koenig" <ark at acm.org> wrote:

>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.  Right now, I can say
>
>    i = iter(d)
>
>and then repeatedly calling i.next() gives us the keys for the elements. 
>But to get the corresponding value requires us to look up the key.
>
>Of course one could define a generator that yields key-value pairs, along 
>the following lines:
>
>    def kviter(d):
>        for i in d:
>            yield i, d[i]
>
>to hide the lookup.  But this yields a tuple even when you don't want it. 
>In other words, I must now write
>
>    for k, v in kviter(d):
>        # whatever
>
>and I can think of situations in which I don't really want both the key and 
>the value all the time.
>
>So what I really want is something like this:
>
>    it = augiter(d)
>    for i in it:
>        if <some condition on i>:
>            foo(it.value())
>
>In other words, I want "it" to support both the next and value methods (or 
>next and something else)
>
>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.
>
It does? (this just occurred to me, so there may be some gotcha ;-)

 >>> class augiter(object):
 ...     def __init__(self, d): self.d = d
 ...     def __iter__(self):
 ...         for k in self.d: self.value = self.d[k]; yield k
 ...
 >>> it = augiter(dict(enumerate('abcd')))
 >>> for i in it:
 ...     if i%2: print i, it.value
 ...
 1 b
 3 d

You could of course store self._value and def value(self):return self._value to be closer to your syntax)

>So my question is: Can you think of an easy way to write something that 
>looks like a generator (using yield), but can also incorporate methods other 
>than next?
>
See above.

Regards,
Bengt Richter



More information about the Python-list mailing list