Message249991
Add an itercm() function that receives an iterable that supports the context manager protocol (e.g. files) and calls enter/exit without having to use the with statement explicitly.
The implementation is pretty straightforward (unless I'm missing something):
def itercm(cm):
with cm:
yield from cm
Example usages:
def cat(fnames):
lines = chain.from_iterable(itercm(open(f)) for f in fnames)
for line in lines:
print(line, end='')
This will close the files as soon as the last line is read.
The __exit__ won't be called until the generator is exhausted, so the user should make sure that it is (if he wants __exit__ to be closed). __exit__ is still called in case of exception.
Attached a clearer example of how it works.
Do you think this would be a good addition to contextlib (or perhaps itertools)?
P.S. I'm also contemplating the idea of having e.g. it = itercm(fname, func=open) to call func lazily once the first next(it) happens, but I haven't thought in detail about the implications of this. I also haven't considered how this interacts with coroutines. |
|
Date |
User |
Action |
Args |
2015-09-06 12:32:15 | ezio.melotti | set | recipients:
+ ezio.melotti, rhettinger, ncoghlan |
2015-09-06 12:32:15 | ezio.melotti | set | messageid: <1441542735.79.0.482816688867.issue25014@psf.upfronthosting.co.za> |
2015-09-06 12:32:15 | ezio.melotti | link | issue25014 messages |
2015-09-06 12:32:15 | ezio.melotti | create | |
|