[Python-ideas] BackupFile

Terry Reedy tjreedy at udel.edu
Mon Jun 25 22:33:07 CEST 2012


On 6/25/2012 8:17 AM, Kim Gräsman 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?

It seems to me that what you actually *want* to do, given your other 
responses, is to make a temporary altered copy of the settings file and 
get the programs to use the *copy*. That way, other users would see the 
original undistrubed and a crash would at worst leave the copy 
undeleted. (Whether you want to copy alterations back is a different 
matter.) I presume the problem is that the program has the name of the 
settings file hard-coded. One possibility might be to run the program in 
a virtual environment with its temporary copy. (But I have 0 experience 
with that. I only know that venv has been added to 3.3.)

-- 
Terry Jan Reedy







More information about the Python-ideas mailing list