Skip to content

Instantly share code, notes, and snippets.

@rmartinjak
Created March 20, 2014 10:29
Show Gist options
  • Save rmartinjak/9660973 to your computer and use it in GitHub Desktop.
Save rmartinjak/9660973 to your computer and use it in GitHub Desktop.
import functools
import contextlib
def cmwrap(cm, *cmargs, **cmkwargs):
"""Decorator wrapping a context manager around a function call."""
def wrapper(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
with cm(*cmargs, **cmkwargs):
return f(*args, **kwargs)
return wrapped_f
return wrapper
@contextlib.contextmanager
def verbose(before, after):
print(before)
yield
print(after)
@cmwrap(verbose, "hello", "bye")
def foo(bar):
print(bar)
if __name__ == '__main__':
foo("doing something")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment