Skip to content

Instantly share code, notes, and snippets.

@ionelmc
Created October 30, 2013 17:44
Show Gist options
  • Select an option

  • Save ionelmc/7236919 to your computer and use it in GitHub Desktop.

Select an option

Save ionelmc/7236919 to your computer and use it in GitHub Desktop.
def monkeypatch(mod, what):
"""
Patch function named <what> from module <mod> to run the decorated function after <what> completes.
Eg::
@monkeypatch(os, 'forkpty')
def patched_forkpty(pid_fd):
pid, fd = pid_fd
if not pid:
fixup_stuff()
return pid, fd
"""
old = getattr(mod, what)
def decorator(func):
def patch():
ret = old()
try:
func(ret)
except:
traceback.print_exc()
return ret
setattr(mod, what, patch)
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment