Last active
August 29, 2015 14:06
-
-
Save vmeyet/77aeb8c038f0aecc150d to your computer and use it in GitHub Desktop.
context_manager to decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
from contextlib import contextmanager | |
def context_to_decorator(context_manager): | |
def decorator_maker(*args_context, **kwargs_context): | |
def decorator(func): | |
@functools.wraps(func) | |
def wrapped(*args, **kwargs): | |
with context_manager(*args_context, **kwargs_context): | |
ret_val = func(*args, **kwargs) | |
return ret_val | |
return wrapped | |
return decorator | |
return decorator_maker | |
@contextmanager | |
def thisiscontext(before, after): | |
print('Before: %s' % before) | |
try: | |
yield | |
finally: | |
print('After: %s' % after) | |
thisisdecorator = context_to_decorator(thisiscontext) | |
# ----------------------------------------------- | |
def test_context_manager(): | |
with thisiscontext('I preceed everything', 'Im at the end of anything'): | |
print 'manager' | |
@thisisdecorator('I preceed everything', 'Im at the end of anything') | |
def test_decorator(): | |
print 'decorator' | |
test_context_manager() | |
test_decorator() | |
# Before: I preceed everything | |
# manager | |
# After: Im at the end of anything | |
# Before: I preceed everything | |
# decorator | |
# After: Im at the end of anything |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment