Skip to content

Instantly share code, notes, and snippets.

@mwhooker
Forked from ieure/save.py
Created November 17, 2009 02:00
Show Gist options
  • Save mwhooker/236551 to your computer and use it in GitHub Desktop.
Save mwhooker/236551 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