General way to add persistence to a class in Python The idea here is to write a function that gives you back a persistent version of a class that you supply. So you if you run

PersistentList = make_persistent(list, "PersistentList", ['append', 'extend', 'insert', 'pop', 'remove', 'reverse', 'sort'])


You will get back a class that behaves like a list but automatically persists itself after each operation. So given this test code:

import time
def get_hhmmss():
    return time.strftime('%H:%M:%S', time.localtime())

def test_list():
    PersistentList = make_persistent(list, "PersistentList", get_mutators(list, tuple))
    filepath = os.path.expanduser("~/Desktop/test_list")
    with contextlib.closing(PersistentList(filepath)) as pl:
        pl.append(get_hhmmss())
        pl += ['foo']
        pl += ['bar']
        print(pl)

def test_set():
    PersistentSet = make_persistent(set, "PersistentSet", get_mutators(set, frozenset))
    filepath = os.path.expanduser("~/Desktop/test_set")
    with contextlib.closing(PersistentSet(filepath)) as ps:
        ps.add(get_hhmmss())
        ps.add('spam')
        print(sorted(ps))


You can get this output:

&gt;&gt;&gt; test_set()
['21:38:27', 'spam']
&gt;&gt;&gt; test_set()
['21:38:27', '21:38:31', 'spam']
&gt;&gt;&gt; test_set()
['21:38:27', '21:38:31', '21:38:34', 'spam']
&gt;&gt;&gt; test_list()
['21:38:39', 'foo', 'bar']
&gt;&gt;&gt; test_list()
['21:38:39', 'foo', 'bar', '21:38:43', 'foo', 'bar']
&gt;&gt;&gt; test_list()
['21:38:39', 'foo', 'bar', '21:38:43', 'foo', 'bar', '21:38:47', 'foo', 'bar']


Here's the code that accomplishes it. I ask in part because I'm tempted to try to share this but assume that if it were a reasonable way to do things it would be out there by now.

import pickle, errno, os, functools, contextlib

def touch_new(filepath):
    "Will fail if filepath already exists, or if relevant directories don't already exist"
    os.close(os.open(filepath, os.O_WRONLY | os.O_CREAT | os.O_EXCL))

def get_mutators(mutable_class, frozen_class):
    "Convenience function for identifying mutators. Methods such as __iadd__ won't wrap properly so this function throws them out; you'll need to call `_save` or `close` to sync after such operations"
    def qualifying_methodname(methodname):
        return not(methodname.startswith("__") and methodname.endswith("__"))    
    return sorted(mn for mn in set(dir(mutable_class)) - set(dir(frozen_class)) if qualifying_methodname(mn))


# Inspiration: http://stackoverflow.com/a/9449852/2829764
def make_persistent(original_class, new_classname, mutator_methodnames):
    class NewClass(original_class):
        def __init__(self, filepath):
            self._filepath = filepath
            self._closed = False
            try:
                with open(filepath, "rb") as ifile:
                    loaded = pickle.load(ifile)
                if type(loaded) != original_class: # Don't even allow subclasses
                    raise TypeError("{} exists but does not contain a {}".format(filepath, original_class))
                original_class.__init__(self, loaded)
            except IOError as ioe:
                if ioe.errno != errno.ENOENT:
                    raise
                touch_new(filepath)
                original_class.__init__(self)
            for attr in mutator_methodnames:
                setattr(self, attr, self._autosave(getattr(self, attr)))
        def _autosave(self, func):
            @functools.wraps(func)
            def _func(*args, **kwargs):
                if self._closed:
                    raise ValueError("Invalid operation on closed "+self.__class__)
                ret = func(*args, **kwargs)
                self._save()
                return ret
            return _func
        def _save(self):
            pickle.dump(original_class(self), open(self._filepath, "wb"))
        def close(self):
            if not self._closed:
                self._save()
                self._closed = True
    NewClass.__name__ = new_classname
    return NewClass
No time to do a proper review, but some quick notes:


There are no docstrings! How am I supposed to use your code?
Doesn't follow the Python style guide (PEP8): in particular, line lengths are too long, so we have to scroll horizontally to read it here.
You should use super to call superclass methods, otherwise your code won't play nicely with multiple inheritance.
This relies on original_class.__init__ taking one optional argument which is copied to self. This seems rather inflexible: it works for some built-in constructors like list but it is not very general. It would be better to leave __init__ alone and use a factory function to do the construction.
It seems clumsy to have to specify the names of all the methods that you need. Python has the tools (dir, __getattribute__, etc.) to avoid this.
Copying attributes from one object to another works for methods but not for properties.
It would be better to actually use the context manager protocol (__enter__ and __exit__) and not contextlib.closing, which requires the object to have a close method which might conflict with original_class.close.
Consider using three-argument type instead of making a class with the wrong name and then rewriting its __name__ attribute.
At the moment you write the object to disk after every change, which is costly. Better to postpone this until the object is finished with.
Consider saving the object via the __del__ method.
Test cases should be organized into unit tests so they are runnable via the unittest module.
Consider catching FileNotFoundError instead of catching IOError and then re-raising if the error code is not ENOENT.