Augmented generators?

Andrew Koenig ark at acm.org
Tue Jan 10 13:37:13 EST 2006


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.

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?





More information about the Python-list mailing list