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
теперь вы можете сделать:
mydeco = Decontext(some_context_manager)
, что позволяет как
@mydeco
def foo(...):
do_bar()
foo(...)
, так и
with mydeco:
do_bar()