context managers inline?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Mar 11 01:09:34 EST 2016


Chris Angelico writes:

> On Fri, Mar 11, 2016 at 5:33 AM, Neal Becker 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.

Make the string look like a file object to the load function:

import io

def clopen(fn, mode = 'r', encoding = None):
    with open(fn, mode = mode, encoding = encoding) as f:
        ModeIO = io.BytesIO if 'b' in mode else io.StringIO
        return ModeIO(f.read())

x = load(clopen('my-file', 'rb'))



More information about the Python-list mailing list