[Python-ideas] With expressions

Ken Hilton kenlhilton at gmail.com
Thu Aug 2 05:35:11 EDT 2018


Hi, I don't know if someone has already suggested this before, but here
goes:

With expressions allow using the enter/exit semantics of the with statement
inside an expression context. Examples:

    contents = f.read() with open('file') as f #the most obvious one
    multiplecontents = [f.read() with open(name) as f for name in names]
#reading multiple files

I don't know if it's worth making the "as NAME" part of the with mandatory
in an expression - is this a valid use case?

    data = database.selectrows() with threadlock

Where this would benefit: I think the major use case is `f.read() with
open('file') as f`. Previous documentation has suggested
`open('file').read()` and rely on garbage collection; as the disadvantages
of that became obvious, it transitioned to a method that couldn't be done
in an expression:

    with open('file') as f:
        contents = f.read()

Therefore `f.read() with open('file') as f`, I think, would be much
welcomed as the best way to read a file in an expression.

For those wondering about the scope semantics of the "as NAME", I think
they would be identical to the scope semantics of the "for" expression -
i.e. these are legal:

    contents = f.read() with open('file') as f
    grid = [[i] * 4 for i in range(4)]

But these are not:

    contents = f.read() with open('file') as f
    f.seek(0)
    grid = [[i] * 4 for i in range(4)]
    grid[i][i] = 4

Is this a good idea? Are there some subtleties I've failed to explain?
Please let me know.

Sharing,
Ken Hilton
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180802/942e0ee7/attachment.html>


More information about the Python-ideas mailing list