関数呼び出しの前後でオブジェクトの属性を保存するデコレータ

def save_attrs(getter, attrs):
    def inner_decorator(f):
        def decorated(*args, **kw):
            obj = getter()
            saved_attrs = {}
            for key, val in attrs.iteritems():
                if hasattr(obj, key):
                    saved_attrs[key] = getattr(obj, key)
                setattr(obj, key, val)
            try:
                return f(*args, **kw)
            finally:
                for key in attrs.iterkeys():
                    if saved_attrs.has_key(key):
                        setattr(obj, key, saved_attrs[key])
                    else:
                        delattr(obj, key)
        return decorated
    return inner_decorator

こうやって使う

@save_attrs(lambda: metadata.engine, {'echo': False})
def setup_db(session):
    metadata.create_all()
    sync_db(metadata)