Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104585

Re: context managers inline?

Path csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail
From Jussi Piitulainen <jussi.piitulainen@helsinki.fi>
Newsgroups comp.lang.python
Subject Re: context managers inline?
Date Fri, 11 Mar 2016 08:09:34 +0200
Organization A noiseless patient Spider
Lines 30
Message-ID <lf560wtczq9.fsf@ling.helsinki.fi> (permalink)
References <nbselg$he9$1@ger.gmane.org> <mailman.154.1457641060.15725.python-list@python.org>
Mime-Version 1.0
Content-Type text/plain; charset=us-ascii
Injection-Info mx02.eternal-september.org; posting-host="305c68510616a2e7ac08bcd2ff1598bd"; logging-data="11229"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19AKqqwhsaPCC8RW6OCNcdoVK9+GhJKSZk="
User-Agent Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux)
Cancel-Lock sha1:1ifPRdX+jQST6mYH207wkjGXAhw= sha1:8bS4kXUh8p8ETc5MflU1mhM55k4=
Xref csiph.com comp.lang.python:104585

Show key headers only | View raw


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 | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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