# Adding atomicwrite in stdlib

**URL:** <https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899>\
**Category:** Ideas\
**Created:** [November 12, 2021, 6:28am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899 "2021-11-12T06:28:03Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![malemburg](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/malemburg/32/50_2.png) [@malemburg](https://discuss.python.org/u/malemburg)\
**Post date:** [November 16, 2021, 9:09am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/21 "2021-11-16T09:09:16Z")

</div>

There were many suggestions in the os.workdir() thread I had started on  
python-ideas and people could not agree (e.g. os, os.path, pathlib,  
shutils, contextlib). My initial idea was to have it in the os module,  
next to os.chdir() and with a different name.

FWIW, I think contextlib is as good as any module and it also  
underlines that the symbol refers to a context manager rather than  
a standard function - something which is not always apparent from  
looking just at the function names or the documentation (e.g.  
the built-in open() doesn’t even mention that the returned file  
object can be used as a context manager).

---

<div class="post-metadata">

**Author:** ![ncoghlan](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ncoghlan/32/14266_2.png) [@ncoghlan](https://discuss.python.org/u/ncoghlan)\
**Post date:** [November 17, 2021, 2:22pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/22 "2021-11-17T14:22:23Z")

</div>

For an earlier bikeshed on this topic: [Issue 8604: Adding an atomic FS write API - Python tracker](https://bugs.python.org/issue8604)

The main reason I still believe this is a feature worthy of the standard library is that without it, even something as simple as “process A periodically writes a file, process B periodically reads it” is unreliable, since process B may try to access the file when process A is halfway through writing it.

By only offering in-place file modification by default, we’re setting new users up to run into a well known problem where the patterns for solving it are far from obvious (e.g. why it matters that the temp file be created in the same directory as the target file)

At my current workplace, we ended up with a two layer API:

- An “atomic\_write” context manager
- A “set\_file\_contents” helper function

The first one is the non-obvious piece that I think is worthy of the stdlib, while the latter probably fails the “not every 3 line helper function needs to be in the stdlib” test.

(FWIW, I think “shutil.staged\_write” would be fine as a name, emphasising the body of the context manager over the end of it. We’d still want to use the phrase “atomic write” somewhere in the documentation, though)

---

<div class="post-metadata">

**Author:** ![ncoghlan](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ncoghlan/32/14266_2.png) [@ncoghlan](https://discuss.python.org/u/ncoghlan)\
**Post date:** [November 17, 2021, 2:28pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/23 "2021-11-17T14:28:42Z")

</div>

Regarding the boundaries between contextlib and shutil: they’re definitely blurry, but a rough rule of thumb is that contextlib definitely shouldn’t affect anything other than the running process.

So redirecting standard streams and changing the current working directory is reasonable (albeit still debatable), but creating files is a definite “No, put it in shutil instead”.

---

<div class="post-metadata">

**Author:** ![steven.daprano](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/steven.daprano/32/1083_2.png) [@steven.daprano](https://discuss.python.org/u/steven.daprano)\
**Post date:** [November 18, 2021, 4:44am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/24 "2021-11-18T04:44:11Z")

</div>

Antoine Pitrou:

“I would never go and look in `contextlib` for OS-related utilities.”

But would you look in contextlib for a context manager?

---

<div class="post-metadata">

**Author:** ![pitrou](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pitrou/32/28_2.png) [@pitrou](https://discuss.python.org/u/pitrou)\
**Post date:** [November 18, 2021, 8:29am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/25 "2021-11-18T08:29:38Z")

</div>

> [@steven.daprano](#):
>
> But would you look in contextlib for a context manager?

Would you look in `functools` for a random function?  
I don’t, and I don’t look into `contextlib` for random context managers (and there isn’t a `classlib` module where I can look for random classes, either).

---

<div class="post-metadata">

**Author:** ![chrish](https://avatars.discourse-cdn.com/v4/letter/c/6de8d8/32.png) [@chrish](https://discuss.python.org/u/chrish)\
**Post date:** [November 19, 2021, 4:52am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/26 "2021-11-19T04:52:24Z")

</div>

Yes. I was coming here to say this. The individual writes are not necessarily atomic, but the whole file is. From the point of view of other processes, it goes from not existing / being there with some old content directly to being there with new content, with nothing in between those two states. So, something like `atomicfile` (maybe with underscore in the middle?) would feel right to me.

---

<div class="post-metadata">

**Author:** ![ncoghlan](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ncoghlan/32/14266_2.png) [@ncoghlan](https://discuss.python.org/u/ncoghlan)\
**Post date:** [November 22, 2021, 11:01pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/27 "2021-11-22T23:01:08Z")

</div>

Despite using “atomic write” as the name for my own staged write implementations, this thread made me realise that there is a major problem with the name: the “atomic” property doesn’t hold in the presence of multiple writers. Truly atomic operations (think atomic increments and decrements in a CPU) include a mechanism to block other writers to ensure two different writers won’t use the same starting state for their modifications.

While one writer, multiple readers is a common underlying assumption in “atomic” write implementations, the key advantage I see to the suggested “staged\_write” name is that the name is correct independent of the number of writers (and helps convey why having multiple writers would be a bad idea).

The feature could also theoretically be used as the basis for a future true “atomic\_write” implementation in the multiprocessing module, although I personally doubt we’d ever add that (once you need multiple writers, it’s usually worth reaching for sqlite instead of a flat file, and file locking has enough nasty failure modes that it’s hard to create abstract solutions that don’t end up looking like some form of database).

---

<div class="post-metadata">

**Author:** ![pitrou](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pitrou/32/28_2.png) [@pitrou](https://discuss.python.org/u/pitrou)\
**Post date:** [November 23, 2021, 9:21am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/28 "2021-11-23T09:21:21Z")

</div>

> [@ncoghlan](#):
>
> Despite using “atomic write” as the name for my own staged write implementations, this thread made me realise that there is a major problem with the name: the “atomic” property doesn’t hold in the presence of multiple writers.

I’m not sure what you mean by that, because multiple writers actually _should_ be fine with such an API. This is why it works for e.g. the JIT caching example I gave: you can have multiple independent processes updating a given cache entry at the same time, and the end result will be correct.

It is also how bytecode caching is implemented, btw, and you can be sure that multiple writers being a problem would have resulted in hundreds of bug reports over the years:

> <https://github.com/python/cpython/blob/d82f2caf942fa8b94e797a2f116ee54ec303c2df/Lib/importlib/_bootstrap_external.py#L185-L204>

---

<div class="post-metadata">

**Author:** ![malemburg](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/malemburg/32/50_2.png) [@malemburg](https://discuss.python.org/u/malemburg)\
**Post date:** [November 23, 2021, 9:52am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/29 "2021-11-23T09:52:31Z")

</div>

The rename is the only atomic part in the whole implementation,  
which is why I believe that using the term transaction is more  
accurate.

In database transactions, the .commit() or .rollback()  
makes the changes appear for others (modulo transaction isolation  
settings and some other details, but let’s leave those aside).

Multiple writers will each get a different temporary file name  
and write to this name. And all will eventually rename this file  
to the final name.

Now, if all writers write the same content (as in the bytecode  
example Antoine gave), there’s no problem. The inode of the file  
will change, but not its contents.

If, however, they write different content, the final state of  
the file will be undefined, since it is not clear which of the  
writers will run the os.rename() last.

And the writers won’t notice on Unix, since os.rename() replaces  
the file, even if it exists.

On Windows, the situation is different: os.rename() won’t  
overwrite existing files.

There are situations where one or the other is better. On Unix,  
you can use hardlinks to get similar behavior to Windows,  
if you want an error raised for existing files.

---

<div class="post-metadata">

**Author:** ![pitrou](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pitrou/32/28_2.png) [@pitrou](https://discuss.python.org/u/pitrou)\
**Post date:** [November 23, 2021, 10:04am UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/30 "2021-11-23T10:04:53Z")

</div>

> [@malemburg](#):
>
> On Windows, the situation is different: os.rename() won’t  
> overwrite existing files.

This uses `os.replace()`, which does.

---

<div class="post-metadata">

**Author:** ![tiran](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tiran/32/48_2.png) [@tiran](https://discuss.python.org/u/tiran)\
**Post date:** [November 23, 2021, 12:36pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/31 "2021-11-23T12:36:58Z")

</div>

> [@pitrou](#):
>
> This uses `os.replace()`, which does.

AFAIK only on POSIX, not on Windows.

---

<div class="post-metadata">

**Author:** ![pitrou](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pitrou/32/28_2.png) [@pitrou](https://discuss.python.org/u/pitrou)\
**Post date:** [November 23, 2021, 12:55pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/32 "2021-11-23T12:55:36Z")

</div>

> [@tiran](#):
>
> > [@pitrou](#):
> >
> > This uses `os.replace()` , which does.
> 
> AFAIK only on POSIX, not on Windows.

No.

> If _dst_ exists and is a file, it will be replaced silently if the user has permission.

---

<div class="post-metadata">

**Author:** ![tiran](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tiran/32/48_2.png) [@tiran](https://discuss.python.org/u/tiran)\
**Post date:** [November 23, 2021, 1:10pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/33 "2021-11-23T13:10:35Z")

</div>

The documentation does not promise that `os.replace` is atomic on Windows, only POSIX.

> Rename the file or directory _src_ to _dst_ . If _dst_ is a directory, [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) will be raised. If _dst_ exists and is a file, it will be replaced silently if the user has permission. The operation may fail if _src_ and _dst_ are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

---

<div class="post-metadata">

**Author:** ![pitrou](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pitrou/32/28_2.png) [@pitrou](https://discuss.python.org/u/pitrou)\
**Post date:** [November 23, 2021, 1:35pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/34 "2021-11-23T13:35:14Z")

</div>

> [@tiran](#):
>
> The documentation does not promise that `os.replace` is atomic on Windows, only POSIX.

Ok, so you were making an unrelated point while replying to a message that did not talk about atomicity but about overwriting 😉

It is a good point however. It is true that [MoveFileEx](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa) does not make any promise about atomicity. It will certainly not be able to when crossing filesystems, which makes it important to remain on the same filesystem.

---

<div class="post-metadata">

**Author:** ![ncoghlan](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ncoghlan/32/14266_2.png) [@ncoghlan](https://discuss.python.org/u/ncoghlan)\
**Post date:** [November 23, 2021, 2:46pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/35 "2021-11-23T14:46:21Z")

</div>

> [@pitrou](#):
>
> I’m not sure what you mean by that, because multiple writers actually _should_ be fine with such an API. This is why it works for e.g. the JIT caching example I gave: you can have multiple independent processes updating a given cache entry at the same time, and the end result will be correct.

True, I was conflating atomic writes in general, with a specific use case for them: staged updates, where the write is preceded by a content read.

For that usage to be safe, there can only be one process staging an update at any point in time.

If the source data for the write is independent of the previously written data, then yes, the atomicity holds for multiple writers.

---

<div class="post-metadata">

**Author:** ![pf\_moore](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/pf_moore/32/35_2.png) [@pf\_moore](https://discuss.python.org/u/pf_moore)\
**Post date:** [November 23, 2021, 3:58pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/36 "2021-11-23T15:58:39Z")

</div>

> [@ncoghlan](#):
>
> I was conflating atomic writes in general, with a specific use case for them: staged updates, where the write is preceded by a content read.

I’m not sure if you’re proposing any change to the API here. My feeling is that the semantics being proposed are straightforward, and easily described as “open a new temporary file, do all writes off to the side, then put the new content in place in an atomic action on close”. Anything more complex is specialised enough to _not_ need to be in the stdlib.

If you’re enumerating cases where there might be more complexity that this basic model might not be able to handle, then that’s fine. If you’re proposing that the scope be extended to handle those cases, then I’m not quite clear on the details of what your concerns are - but my initial reaction is likely to be “no, lets keep the scope as it is”.

---

<div class="post-metadata">

**Author:** ![storchaka](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/storchaka/32/217_2.png) [@storchaka](https://discuss.python.org/u/storchaka)\
**Post date:** [November 23, 2021, 10:17pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/37 "2021-11-23T22:17:24Z")

</div>

There is a reason of placing this function in the `tempfile` module. The implementation requires `tempfile`, but `tempfile` imports `shutil`, so adding it in `shutil` would create a loop.

---

<div class="post-metadata">

**Author:** ![ncoghlan](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/ncoghlan/32/14266_2.png) [@ncoghlan](https://discuss.python.org/u/ncoghlan)\
**Post date:** [December 1, 2021, 12:36pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/38 "2021-12-01T12:36:02Z")

</div>

> [@pf\_moore](#):
>
> If you’re enumerating cases where there might be more complexity that this basic model might not be able to handle, then that’s fine. If you’re proposing that the scope be extended to handle those cases, then I’m not quite clear on the details of what your concerns are - but my initial reaction is likely to be “no, lets keep the scope as it is”.

It’s the former case, as I’m just explaining why I think the “atomic” term can be misleading, and hence why the “staged write” naming may be preferable: “atomic” CPU operations refer to atomic “read and update” instructions that can be safely performed from multiple writers without risking lost updates.

Staged file writes are different, as if the new output depends on the previous output, then you need to limit yourself to a single writer to avoid potentially lost writes. You can only easily tolerate multiple writers if each new version of the file is generated independently from other sources.

---

<div class="post-metadata">

**Author:** ![Monarch](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/monarch/32/18530_2.png) [@Monarch](https://discuss.python.org/u/Monarch)\
**Post date:** [September 22, 2024, 12:37pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/39 "2024-09-22T12:37:44Z")

</div>

The [atomicwrites](https://github.com/untitaker/python-atomicwrites) library has been unmaintained and archived since 2022. I really do think we need this in stdlib now more than ever.

---

<div class="post-metadata">

**Author:** ![mcepl](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/mcepl/32/24095_2.png) [@mcepl](https://discuss.python.org/u/mcepl)\
**Post date:** [September 22, 2024, 3:18pm UTC](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899/40 "2024-09-22T15:18:43Z")

</div>

I don’t get the logic here: there is a library, which you apparently need. That library has been abandoned. Instead of forking it and maintaining it yourself, you want somebody else to put it to the standard library and maintain it for you? I am not sure if it is how it works.

Better idea: take over the library, improve it, maintain it, show how successful and necessary for others the idea is, and then come to the standard library with all your users and experience in maintaining it.

[Previous page](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899.md?page=1)

[Next page](https://discuss.python.org/t/adding-atomicwrite-in-stdlib/11899.md?page=3)
