Skip to content

Instantly share code, notes, and snippets.

@ieure
Created November 16, 2009 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ieure/236382 to your computer and use it in GitHub Desktop.
Save ieure/236382 to your computer and use it in GitHub Desktop.
from contextlib import contextmanager
@contextmanager
def save(obj, attrs=None):
"""Save attributes of an object, then restore them.
Example:
import breakfast
with save(breakfast, ('eggs', 'bacon')):
breakfast.Eggs = lambda: "Eggs"
"""
orig_attrs = {}
for attr in attrs:
orig_attrs[attr] = getattr(obj, attr)
try:
yield
finally:
for attr in attrs:
try:
setattr(obj, attr, orig_attrs[attr])
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment