[Python-ideas] `to_file()` method for strings

Michel Desmoulin desmoulinmichel at gmail.com
Mon Mar 28 14:31:20 EDT 2016


Woops, sent it to only one person.

Le 28/03/2016 19:52, Michel Desmoulin a écrit :
> 
> 
> Le 28/03/2016 19:24, Alexander Belopolsky a écrit :
>>
>> On Mon, Mar 28, 2016 at 12:40 PM, Chris Barker <chris.barker at noaa.gov
>> <mailto:chris.barker at noaa.gov>> wrote:
>>
>>     but:
>>
>>     data = open("foo.txt", "r", close_after_use=True).read()
>>
>>     and 
>>
>>     infile = open("foo.txt", "r", close_after_use=True)
>>     data = infile.read()
>>
>>     look exactly the same to the file object itself, it has no idea when
>>     the user is done with it.
>>
>>
>> It is my understanding that under the "close_after_use" proposal, infile
>> will be closed by .read() in both cases.
>>
>> Still, I don't like this idea.  I puts action specification (close) too
>> far from where the action is taken.  The two-line example already makes
>> me uncomfortable and imagine if infile is passed through several layers
>> of function calls before infile.read() is called.
>>
>> I would rather see read_and_close() and write_and_close() convenience
>> methods for file objects:
>>
>>  data = open("foo.txt").read_and_close()
> 
> All those area already part of the stdlib though:
> 
>>>> import pathlib
>>>> pathlib.Path('/tmp/foo').write_text('bar')
> 3
>>>> pathlib.Path('/tmp/foo').read_text()
> 'bar'
> 
> Hence the other discussion about making a p-string, so you can have Path
> object literal notation and do:
> 
>>>> p'/tmp/foo'.write_text('bar')
> 
> An no imports.
> 
> I like the idea of having path literals (alhough I wish for a much
> improved pathlib), it would be handy for scripting, shell sessions, data
> mangling, etc.
> 
> But progamming is now less and less about files : web API, phones APIS,
> DB, ESB... So I'm wondering if it's not trying to fight a century old
> battle.
> 
> 
>>
>>
>> _______________________________________________
>> 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