Does it make sense to put the file in place if the context exits with an exception?
Actually this is what I don't like about the design of python context managers: it puts you, as the author of a context manager, in the position where you may have to worry about failures in the context you manage — and yet it's easy for the author of the context to hide them from you. So maybe stupid is just better.
=== added file 'lib/lp/ archivepublishe r/scripts/ generate_ extra_overrides .py' archivepublishe r/scripts/ generate_ extra_overrides .py 1970-01-01 00:00:00 +0000 archivepublishe r/scripts/ generate_ extra_overrides .py 2011-12-06 15:03:58 +0000
--- lib/lp/
+++ lib/lp/
+class AtomicFile:
+ """Facilitate atomic writing of files."""
+
+ def __init__(self, filename):
+ self.filename = filename
+ self.fd = open('%s.new' % self.filename, 'w')
+
+ def __enter__(self):
+ return self.fd
+
+ def __exit__(self, exc_type, exc_value, exc_tb):
+ self.fd.close()
+ os.rename('%s.new' % self.filename, self.filename)
Does it make sense to put the file in place if the context exits with an exception?
Actually this is what I don't like about the design of python context managers: it puts you, as the author of a context manager, in the position where you may have to worry about failures in the context you manage — and yet it's easy for the author of the context to hide them from you. So maybe stupid is just better.