[Python-ideas] With expressions

Todd toddrjen at gmail.com
Fri Aug 3 13:56:41 EDT 2018


On Thu, Aug 2, 2018 at 5:35 AM, Ken Hilton <kenlhilton at gmail.com> wrote:

> 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
>
>
If this is a common enough operation for you, it would be trivially easy to
just write a function that does this.  There is already a module on pypi
that has this function: read_and_close.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180803/74989ab4/attachment-0001.html>


More information about the Python-ideas mailing list