[Python-ideas] BackupFile

Mike Graham mikegraham at gmail.com
Mon Jun 25 15:42:22 CEST 2012


On Mon, Jun 25, 2012 at 8:17 AM, Kim Gräsman <kim at mvps.org> wrote:
> Hello,
>
> I'm new here, so forgive me if this has been discussed before or is off-topic.
>
> I came up with a mechanism that I thought might be useful in the
> Python standard library -- a scope-bound self-restoring backup file. I
> came to this naïve implementation;
>
> --
> class BackupError(Exception):
>   pass
>
> class Backup:
>   def __init__(self, path):
>       if not os.path.exists(path) or os.path.isdir(path):
>           raise BackupError("%s must be a valid file path" % path)
>
>       self.path = path
>       self.backup_path = None
>
>   def __enter__(self):
>       self.backup()
>
>   def __exit__(self, type, value, traceback):
>       self.restore()
>
>   def _generate_backup_path(self):
>       tempdir = tempfile.mkdtemp()
>       basename = os.path.basename(self.path)
>       return os.path.join(tempdir, basename)
>
>   def backup(self):
>       backup_path = self._generate_backup_path()
>       shutil.copy(self.path, backup_path)
>       self.backup_path = backup_path
>
>   def restore(self):
>       if self.backup_path:
>           # Write backup back onto original
>           shutil.copy(self.backup_path, self.path)
>           shutil.rmtree(os.path.dirname(self.backup_path))
>           self.backup_path = None
> --
>
> Backups are intended to be scope-bound like so:
>
>  with Backup(settings_file):
>    rewrite_settings(settings_file)
>    do_something_else()
>
> I even managed to use it with the @contextmanager attribute, to allow this:
>
>  with rewrite_settings(settings_file):
>    do_something_else()
>
> So, open questions;
>
> - Would something like this be useful outside of my office?
> - Any suggestions for better names?
> - This feels like it belongs in the tempfile module, would you agree?
> - What's lacking in the implementation? Have I done something
> decidedly non-Pythonic?
>
> Thanks,
> - Kim


I like the basic idea, but if we do something like this, it would be
useful to have read access to the old version of the file while you
are writing out the new version that might become permanent.

If I was to implement something like this, I'd use a "right a
temporary file then copy it overwriting the old one when I'm done"
approach rather than a "back up the file" approach so that if the
process dies for a reason Python can't clean up after (like due to
SIGKILL), the half-written file doesn't remain.

I don't really like the name Backup but I can't think of a better name
at the moment.

Mike



More information about the Python-ideas mailing list