New submission from Ezio Melotti: 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. ---------- components: Library (Lib) files: itercm-example.txt messages: 249991 nosy: ezio.melotti, ncoghlan, rhettinger priority: normal severity: normal stage: needs patch status: open title: Add contextlib.itercm() type: enhancement versions: Python 3.6 Added file: http://bugs.python.org/file40380/itercm-example.txt _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue25014> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com