[Python-ideas] With expressions

Paul Moore p.f.moore at gmail.com
Thu Aug 2 05:53:22 EDT 2018


On Thu, 2 Aug 2018 at 10:39, Ken Hilton <kenlhilton at gmail.com> wrote:

> 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:

That use case is satisfied by pathlib:

Path('file').read_text()

see https://docs.python.org/3.7/library/pathlib.html#pathlib.Path.read_text

Are there any other use cases? I don't see any real advantage here
other than the non-advantage of being able to write one-liners.
Paul


More information about the Python-ideas mailing list