[Python-ideas] With expressions

Thomas Nyberg ml+python-ideas at thomasnyberg.com
Thu Aug 2 06:23:50 EDT 2018


Is it true that Path('file').read_text() closes the file after the read? 
I think that is the sort of functionality that Ken is asking for.
It's not clear to me by your linked documentation that it does. If it 
does, maybe that should be made more clear in that linked documentation? 
(Of course, maybe it's written there somewhere and I'm just blind...)

Cheers,
Thomas

On 08/02/2018 11:53 AM, Paul Moore wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
> 


More information about the Python-ideas mailing list