Popular recipes tagged "meta:requires=__future__" and "context_manager"http://code.activestate.com/recipes/tags/meta:requires=__future__+context_manager/2010-01-09T07:14:06-08:00ActiveState Code RecipesContext manager for restoring a value (Python)
2010-01-09T07:14:06-08:00George Sakkishttp://code.activestate.com/recipes/users/2591466/http://code.activestate.com/recipes/576977-context-manager-for-restoring-a-value/
<p style="color: grey">
Python
recipe 576977
by <a href="/recipes/users/2591466/">George Sakkis</a>
(<a href="/recipes/tags/contextlib/">contextlib</a>, <a href="/recipes/tags/context_manager/">context_manager</a>).
Revision 8.
</p>
<p>Often one wants to rebind a name or modify a mutable object, perform a bunch of actions and finally restore the name/object to its original state. An example is redirecting stdout/stderr temporarily (<a href="http://www.diveintopython.org/scripts_and_streams/stdin_stdout_stderr.html" rel="nofollow">http://www.diveintopython.org/scripts_and_streams/stdin_stdout_stderr.html</a>). The <em>restoring</em> context manager shown below simplifies this pattern::</p>
<pre class="prettyprint"><code>import sys
# prints in console
print "hello world!"
with restoring('sys.stdout'):
with open('hello.txt', 'w') as sys.stdout:
# prints in file
print "hello world!"
# prints in console again
print "hello world!"
</code></pre>
ChangeDirectory context manager (Python)
2009-01-24T12:41:53-08:00Christophe Simonishttp://code.activestate.com/recipes/users/4166953/http://code.activestate.com/recipes/576620-changedirectory-context-manager/
<p style="color: grey">
Python
recipe 576620
by <a href="/recipes/users/4166953/">Christophe Simonis</a>
(<a href="/recipes/tags/change/">change</a>, <a href="/recipes/tags/chdir/">chdir</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/directory/">directory</a>).
Revision 2.
</p>
<p>A context manager that handle a temporary change of the working directory</p>