Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Jussi Piitulainen Newsgroups: comp.lang.python Subject: Re: context managers inline? Date: Fri, 11 Mar 2016 11:16:05 +0200 Organization: A noiseless patient Spider Lines: 50 Message-ID: References: <87lh5pxyhi.fsf@nightsong.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="305c68510616a2e7ac08bcd2ff1598bd"; logging-data="9955"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+7FwVfkxbhz8qVLhmXhZ/RPYob1QpXVr0=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:TJgu6rYVchvEYCDAwOfVZUckzww= sha1:3qed59w8CtQye1bCI3HOg9ylP48= Xref: csiph.com comp.lang.python:104598 Paul Rubin writes: > Jussi Piitulainen writes: >> return ModeIO(f.read()) > > These suggestions involving f.read() assume the file contents are small > enough to reasonably slurp into memory. That's unlike the original > where "load" receives a stream and might process it piecewise. If you strike that word "reasonably", then yes, of course they do. A _reasonable_ answer to the original question may well be "no", even though it's not strictly true (because load can be written to close the file, because open can be replaced with something that closes the file, or registers the file with some mechanism that closes the file at a convenient time, assuming the programmer ensures that that time eventually comes, because one can trust the memory management system to close the file, assuming the unreachable file object is eventually collected). I think the following was also effectively given by someone already. It would work, _assuming_ that the user is happy to use higher order functions and especially _lambda_ (or restrict themself to always use unary functions in place of their load, which to me is the most bizarre suggestion so far). My impression of the Python community is that there is some resistance to higher order functions and _especially_ to lambda. def load(o, length = 1): return [ line[:length] for line in o ] def closing(p, o): with o as f: return p(f) x = closing(load, open('Chipsta/Demo.org', mode = 'rb')) y = closing(load, open('Chipsta/Demo.org', encoding = 'UTF-8')) print(x) print(y) x = closing(lambda o: load(o, 2), open('Chipsta/Demo.org', mode = 'rb')) y = closing(lambda o: load(o, 2), open('Chipsta/Demo.org', encoding = 'UTF-8')) print(x) print(y) A problem with _every_ solution is that they cannot be idiomatic Python. The idiomatic Python thing is to rearrange the code as a with-statement. I think. (I hedge.)