Skip to content

Instantly share code, notes, and snippets.

@jsocol
Created March 12, 2011 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsocol/867553 to your computer and use it in GitHub Desktop.
Save jsocol/867553 to your computer and use it in GitHub Desktop.
ContextDecorator for Python 2.6/2.7.
from functools import wraps
class ContextDecorator(object):
def __call__(self, fn):
@wraps(fn)
def decorator(*args, **kw):
with self:
return fn(*args, **kw)
def __enter__(self):
# Do whatever setup.
def __exit__(self, type, value, tb):
# Do whatever cleanup.
if any((type, value, tb)):
raise type, value, tb
mycontextdecorator = ContextDecorator()
with mycontextdecorator:
# Do something!
@mycontextdecorator
def myfunc():
# Do something!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment