context managers inline?

Chris Angelico rosuav at gmail.com
Thu Mar 10 15:17:37 EST 2016


On Fri, Mar 11, 2016 at 5:33 AM, Neal Becker <ndbecker2 at gmail.com> wrote:
> Is there a way to ensure resource cleanup with a construct such as:
>
> x = load (open ('my file', 'rb))
>
> Is there a way to ensure this file gets closed?

Yep!

def read_file(fn, *a, **kw):
    with open(fn, *a, **kw) as f:
        return f.read()

Now you can ensure resource cleanup, because the entire file has been
read in before the function returns. As long as your load() function
is okay with reading from a string, this is effective.

Alternatively, push the closing the other way: pass a file name to
your load() function, and have the context manager in there.

If you don't do it one of those ways, the question is: WHEN should the
file be closed? How does Python know when it should go and clean that
up? There's no "end of current expression" rule as there is in C++, so
it's safer to use the statement form, which has a definite end (at the
unindent).

ChrisA



More information about the Python-list mailing list