[Python-ideas] With clauses for generator expressions
abarnert at yahoo.com
Fri Nov 16 20:02:49 CET 2012
I missed this the first time through among all the other alternative suggestions:
Sent from my iPhone
On Nov 15, 2012, at 20:33, Mathias Panzenböck <grosser.meister.morti at gmx.net>
> For now one can do this, which is functional equivalent but adds the overhead of another generator:
> def managed(sequence):
> with sequence:
> for item in sequence:
> yield item
> upperlines = (lines.upper() for line in managed(open('foo', 'r')))
I think this ought to be in itertools in the standard library.
I don't think the extra overhead will be a problem most of the time.
It solves at least the simplest cases for when a with clause would be useful, and it's even a better solution for some cases where you'd write a with statement today.
In some cases you'd have to write things like managed(closing(foo)), but in those cases you probably wouldn't have wanted the with clause, either.
More information about the Python-ideas