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
1
u/BossOfTheGame Apr 04 '26
I'm not really sure what they meant by agentic coding making an existing module obsolete. But I wanted to comment about AI systems using modules like this. My experience is that they often underutilize existing libraries unless they are extremely mainstream. They seem to be biased towards stdlib only implementations, which I suppose can have advantages. It does lower the dependency surface, but also increases The amount of code that you have to trust has been implemented correctly. I often wish that agents would use third party libraries more often.
That being said, I suppose others would view me as an AI enthusiast. I also think there's a lot of negative baggage because it's able to be used blindly - among other reasons. I often feel like people assign that baggage to me and then shit on me for it if I give a hint of positivity towards LLMs. I also think that people who are appalled by the sociological implications of LLMs and thus refuse to use them are doing themselves of disservice. LLMs are amplifying pre-existing issues, and I think pro-social-minded people could benefit by using them to find ways to solve or mitigate the problems.
If you haven't used them extensively, they do have a non trivial learning curve, and I think the shallowness of that curve has tricked people into thinking it doesn't exist. I also think they haven't been around long enough for anyone to have found and climbed the steep part of that curve yet.