Skip to content

Instantly share code, notes, and snippets.

@alecthomas
Last active December 18, 2015 11:59
Show Gist options
  • Save alecthomas/5779354 to your computer and use it in GitHub Desktop.
Save alecthomas/5779354 to your computer and use it in GitHub Desktop.
Monkey patching context manager
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