Latest recipes tagged "contextmanager" and "decorators"http://code.activestate.com/recipes/tags/contextmanager+decorators/new/2010-06-27T15:15:01-07:00ActiveState Code RecipesDecorator and context manager from a single API (Python)
2010-06-27T15:15:01-07:00Michael Foordhttp://code.activestate.com/recipes/users/2183852/http://code.activestate.com/recipes/577273-decorator-and-context-manager-from-a-single-api/
<p style="color: grey">
Python
recipe 577273
by <a href="/recipes/users/2183852/">Michael Foord</a>
(<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/with/">with</a>, <a href="/recipes/tags/with_statement/">with_statement</a>).
Revision 12.
</p>
<p>Create objects that act as both context managers <em>and</em> as decorators, and behave the same in both cases.</p>
<p>Works with Python 2.4 - 2.7 and Python 3. The tests require unittest2 or Python 3.2 to run. (And because the tests use the with statement they won't work with Python 2.4.)</p>
<p>Example:</p>
<pre class="prettyprint"><code>from contextdecorator import ContextDecorator
class mycontext(ContextDecorator):
def __init__(self, *args):
"""Normal initialiser"""
def before(self):
"""
Called on entering the with block or starting the decorated function.
If used in a with statement whatever this method returns will be the
context manager.
"""
def after(self, *exc):
"""
Called on exit. Arguments and return value of this method have
the same meaning as the __exit__ method of a normal context
manager.
"""
</code></pre>
<p>Both before and after methods are optional (but providing neither is somewhat pointless). See the tests for more usage examples.</p>