Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #104585
| From | Jussi Piitulainen <jussi.piitulainen@helsinki.fi> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: context managers inline? |
| Date | 2016-03-11 08:09 +0200 |
| Organization | A noiseless patient Spider |
| Message-ID | <lf560wtczq9.fsf@ling.helsinki.fi> (permalink) |
| References | <nbselg$he9$1@ger.gmane.org> <mailman.154.1457641060.15725.python-list@python.org> |
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'))
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Re: context managers inline? Chris Angelico <rosuav@gmail.com> - 2016-03-11 07:17 +1100
Re: context managers inline? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-03-11 08:09 +0200
Re: context managers inline? Paul Rubin <no.email@nospam.invalid> - 2016-03-10 23:30 -0800
Re: context managers inline? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-03-11 11:16 +0200
csiph-web