I like the creativity of your solution, but my subjective opinion would be that using contextlib.ExitStack() will look cleaner, be more readable, than using the generator since each generator would need to be primed with generator.send(None)
and explicitly closed.
By the way, (even though I think contextlib
will lead to shorter, more readable code), write
could be simplified a little bit:
def write(file, header):
with open(file, 'w') as f:
f.write(header)
while True:
line = (yield)
f.write(line)
return
Note you only need one line = (yield)
instead of two.
Also, instead of priming the generator with generator.send(None)
you could use the coroutine
decorator:
def coroutine(func):
""" http://www.python.org/dev/peps/pep-0342/ """
def wrapper(*args, **kw):
gen = func(*args, **kw)
gen.send(None)
return gen
return wrapper
This is a commonly understood idiom (PEP0342, David Beazley talk) for turning a generator into a coroutine. So decorating your generator with it would also serve the purpose of advertising that write
is a coroutine.