Last active
December 18, 2015 11:59
-
-
Save alecthomas/5779354 to your computer and use it in GitHub Desktop.
Monkey patching context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
@contextmanager | |
def patch(owner, attr, value): | |
"""Monkey patch context manager. | |
with patch(os, 'open', myopen): | |
... | |
""" | |
old = getattr(owner, attr) | |
setattr(owner, attr, value) | |
try: | |
yield getattr(owner, attr) | |
finally: | |
setattr(owner, attr, old) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment