I have a helper class Decontext
that I am using to turn a context manager into a decorator (pyton 2.6).
class Decontext(object):
"""
makes a context manager also act as decorator
"""
def __init__(self, context_manager):
self._cm = context_manager
def __enter__(self):
return self._cm.__enter__()
def __exit__(self, *args, **kwds):
return self._cm.__exit__(*args, **kwds)
def __call__(self, func):
def wrapper(*args, **kwds):
with self:
return func(*args, **kwds)
return wrapper
My contextmanager
takes an argument and I am trying to figure out how to pass that argument when using this decorator ?
@contextmanager
def sample_t(arg1):
print "<%s>" % arg1
yield
This is how I am using it which fails:
my_deco = Decontext(sample_t)
@my_deco(arg1='example')
def some_func()
print 'works'
EDIT:
I would like the Decontext
class to pass all *args
in the context_manager when the __call__
function executes.
Example:
decorator_example = Decontext(sample_t) // I don't want to pass in the argument here but when the decorator is created. How can I modify my class to make this enhancement
Edit 2:
Example of what I expected
my_deco = Decontext(sample_t)
@my_deco(arg1='example')
def some_func()
print 'works'
Expected output:
'example' // running and passing argument to context_manager
'works' // after yield executing some_func