[Python-ideas] BackupFile

Kim Gräsman kim at mvps.org
Mon Jun 25 14:17:29 CEST 2012


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):

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):

   def __exit__(self, type, value, traceback):

   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)
           self.backup_path = None

Backups are intended to be scope-bound like so:

 with Backup(settings_file):

I even managed to use it with the @contextmanager attribute, to allow this:

 with rewrite_settings(settings_file):

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?

- Kim

More information about the Python-ideas mailing list