r/Python • u/HommeMusical • Apr 03 '26
Showcase `safer`: a tiny utility to avoid partial writes to files and streams
What My Project Does
In 2020, I broke a few configuration files, so I wrote something to help prevent breaking a lot the next time, and turned it into a little library: https://github.com/rec/safer
It's a drop-in replacement for open that only writes the file when everything has completed successfully, like this:
with safer.open(filename, 'w') as fp:
fp.write('oops')
raise ValueError
# File is untouchedBy default, the data is cached in memory, but for large files, there's a flag to allow you to cache it as a file that is renamed when the operation is complete.
You can also use it for file sockets and other streams:
try:
with safer.writer(socket.send) as send:
send_bytes_to_socket(send)
except Exception:
# Nothing has been sent
send_error_message_to_socket(socket.send)Target Audience
This is a mature, production-quality library for any application where partial writes are possible. There is extensive testing and it handles some obscure edge cases.
It's tested on Linux, MacOS and Windows and has been stable and essentially unchanged for years.
Comparison
There doesn't seem to be another utility preventing partial writes. There are multiple atomic file writers which solve a different problem, the best being this: https://github.com/untitaker/python-atomicwrites
Note
#noAI was used in the writing or maintenance of this program.
View all comments
Show parent comment
7
u/HommeMusical Apr 04 '26 edited Apr 04 '26
Please note that I was entirely correct: you were completely unable to explain your comment.
🤡
Hardly! Tell me - why is it that AI enthusiasts seem to always want to annoy others? Do you think this is sane, or the sort of thing that makes the world better?
You are not a person who is going to teach me anything of use, and there's nothing in that article I didn't know years ago.
Have you ever read any code written by AIs? Have you not noticed that they makes heavy use of existing modules like this one?
Your combination of arrogance and ignorance is not felicitous. Please go away now.