context managers inline?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Fri Mar 11 04:16:05 EST 2016


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.)



More information about the Python-list mailing list