Augmented generators?

Lonnie Princehouse finite.automaton at gmail.com
Tue Jan 10 14:10:24 EST 2006


AFAIK there's no way to have "yield" produce anything other than a
generator.
You could achieve the syntax you want with a decorator, although under
the hood it would still be iterating over a (key,value) tuples so
there's not really any point.

class GeneratorTupleWrapper:
  def __init__(self, g):
    self.g = g
  def next(self):
    key, self._value = g.next()
    return key
  def value(self):
    return self._value

def magic_generator (func):
  def wrapper(*a, **b):
    return GeneratorTupleWrapper(func(*a, **b))

@magic_generator
def kviter(d):
  for i in d:
    yield i, d[i]

it = kviter(d)
for key in it:
  if <something>:
    foo(it.value())




Also: dict.iteritems() enumerates (key,value) tuples for dictionaries,
so kviter isn't necessary if d is a dictionary.  I don't know the
internal mechanism used by dict for iteritems, but it's a fair bet that
it's more efficient than performing a lookup for every single key.




More information about the Python-list mailing list