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

Nathaniel Smith njs at pobox.com
Wed Mar 23 00:49:26 EDT 2016


On Tue, Mar 22, 2016 at 9:33 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, Mar 23, 2016 at 3:22 PM, Alexander Belopolsky
> <alexander.belopolsky at gmail.com> wrote:
>>
>> On Tue, Mar 22, 2016 at 11:33 PM, Andrew Barnert via Python-ideas
>> <python-ideas at python.org> wrote:
>>>     with tempfile.NamedTemporaryFile('w', dir=os.path.dirname(path),
>>> delete=False) as f:
>>>         f.write(s)
>>>         f.flush()
>>>         os.replace(f.path, path)
>> You've got it wrong, but I understand what you tried to achieve.  Note that
>> the "write to temp and move" trick may not work if your /tmp and your path
>> are mounted on different filesystems.  And with some filesystems it may not
>> work at all, but I agree that it would be nice to have a state of the art
>> atomic write method somewhere in stdlib.
>
> It's specifically selecting a directory for the temp file, so it ought
> to work. However, I'm not certain in my own head of the interaction
> between NamedTemporaryFile with delete=False and os.replace (nor of
> exactly how the latter differs from os.rename); what exactly happens
> when the context manager exits here? And what happens if there's an
> exception in the middle of this and stuff doesn't complete properly?
> Are there points at which this could (a) destroy data by deleting
> without saving, or (b) leave cruft around?
>
> This would be very nice to have as either stdlib or a well-documented recipe.

Also: cross-platform support (Windows Is Different), handling of
permissions, do you care about xattrs?, when you say "atomic" then do
you mean atomic WRT power loss?, ... it's not actually 100% clear to
me that a one-size-fits-all atomic write implementation is possible.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-ideas mailing list