This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ezio.melotti
Recipients ezio.melotti, ncoghlan, rhettinger
Date 2015-09-06.12:32:14
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1441542735.79.0.482816688867.issue25014@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2015-09-06 12:32:15ezio.melottisetrecipients: + ezio.melotti, rhettinger, ncoghlan
2015-09-06 12:32:15ezio.melottisetmessageid: <1441542735.79.0.482816688867.issue25014@psf.upfronthosting.co.za>
2015-09-06 12:32:15ezio.melottilinkissue25014 messages
2015-09-06 12:32:15ezio.melotticreate