Popular recipes tagged "contextmanager"http://code.activestate.com/recipes/tags/contextmanager/2017-06-22T11:57:20-07:00ActiveState Code RecipesVariable Abbreviations (Python) 2017-06-22T11:57:20-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580807-variable-abbreviations/ <p style="color: grey"> Python recipe 580807 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/abbreviations/">abbreviations</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/variables/">variables</a>, <a href="/recipes/tags/with/">with</a>). </p> <p>One sometimes has nice long speaking names vor variables, maybe things like <code>buildingList[foundIndex].height</code>, but would like to address these in a shorter fashion to be used within a formula or similar where lots of longs names tend to confuse any reader trying to understand the formula. Physicists use one-letter names for a reason.</p> <p>For this I wrote a small context provider which allows using short names instead of long ones:</p> <pre class="prettyprint"><code>with Abbr(h=buildingList[foundIndex].height, g=gravitationalConstant): fallTime = sqrt(2 * h / g) endSpeed = sqrt(2 * h * g) print("Fall time:", fallTime) print("End speed:", endSpeed) </code></pre> <p>For longer formulas this can reduce ugly multi-line expressions to clearly readable one-liners.</p> <p>One could use this:</p> <pre class="prettyprint"><code>h = buildingList[foundIndex].height g = gravitationalConstant fallTime = sqrt(2 * h / g) endSpeed = sqrt(2 * h * g) del g, h print("Fall time:", fallTime) print("End speed:", endSpeed) </code></pre> <p>to achieve the same result, but</p> <ul> <li>it would not look as clean and</li> <li>the context provider solves the typical issues like cleanup on exception etc.</li> </ul> <p>Just using local variables without cleanup (like above without the <code>del</code> statement) also is an option of course, but that would clutter the variable name space unnecessarily.</p> <p>CAVEATS: The implementation of <code>Abbr()</code> is a hack. If used as intended and described here, it should work just fine, though. But the hackish nature forces me to mention some things: Since at compile time the compiler decides that the <code>h</code> and <code>g</code> in the example must be global variables (because they aren't assigned in the function), it produces byte code accessing global variables. The context provider changes the global variable structure to fill the needs. (Overridden already existing global variables of the same name get restored properly at context exit.) This means some things:</p> <ul> <li>One cannot have a local variable of the same name in the frame surrounding the context manager.</li> <li>Existing global variables are changed during the time of the context manager; so using names like <code>sys</code> or <code>os</code> for abbreviations might be a bad idea due to side-effects.</li> </ul> Context Manager for an Arbitrary Number of Files in Python (Python) 2017-03-13T13:27:50-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580763-context-manager-for-an-arbitrary-number-of-files-i/ <p style="color: grey"> Python recipe 580763 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/open/">open</a>). Revision 2. </p> <p>The pattern using <code>with</code> together with <code>open()</code> to automatically close a file after leaving the context is well known. To open a fixed number you can simply nest these statements or use the comma notation. For having a context which represents an arbitrary number of open files you can use the <code>ExitStack</code> class, but only for Python 3.3+.</p> <p>For other Python versions I'm using the following class which I named <code>Files</code>. The presented implementation is only for reading files (for keeping it clear). Extending it for having various file modes should not pose a problem.</p> Use PDFWriter with context manager support (Python) 2013-12-16T21:43:27-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/578790-use-pdfwriter-with-context-manager-support/ <p style="color: grey"> Python recipe 578790 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/reportlab/">reportlab</a>, <a href="/recipes/tags/with_statement/">with_statement</a>, <a href="/recipes/tags/xtopdf/">xtopdf</a>). </p> <p>PDFWriter - a core class of the xtopdf toolkit - can now be used with a Python context manager, a.k.a. the Python <strong>with</strong> statement.</p> <p>Code example below. More details here:</p> <p><a href="http://jugad2.blogspot.in/2013/12/xtopdf-pdfwriter-now-has-context.html" rel="nofollow">http://jugad2.blogspot.in/2013/12/xtopdf-pdfwriter-now-has-context.html</a></p> Wrap any iterable context manager so it closes when consumed (Python) 2012-11-19T20:10:35-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/578342-wrap-any-iterable-context-manager-so-it-closes-whe/ <p style="color: grey"> Python recipe 578342 by <a href="/recipes/users/4184316/">Andrew Barnert</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/iterable/">iterable</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/with_statement/">with_statement</a>). </p> <p>There are a few types in Python—most notably, files—that are both iterators and context managers. For trivial cases, these features are easy to use together, but as soon as you need to use the iterator lazily or asynchronously, a with statement won't help. That's where this recipe comes in handy:</p> <pre class="prettyprint"><code>send_async(with_iter(open(path, 'r'))) </code></pre> <p>This also allows you to "forward" closing for a wrapped iterator, so closing the outer iterator also closes the inner one:</p> <pre class="prettyprint"><code>sync_async(line.upper() for line in with_iter(open(path, 'r'))) </code></pre> Context manager to atomically replace a file (Python) 2012-06-17T12:09:49-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578166-context-manager-to-atomically-replace-a-file/ <p style="color: grey"> Python recipe 578166 by <a href="/recipes/users/2033964/">Oren Tirosh</a> (<a href="/recipes/tags/atomic/">atomic</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/replace/">replace</a>). Revision 3. </p> <p>This context manager ensures that a file's content is either replaced atomically with new contents or left unchanged. An exception or other error will not leave it empty or with partial content.</p> Handle exit context manager (Python) 2014-08-01T08:28:07-07:00Giampaolo Rodolàhttp://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/577997-handle-exit-context-manager/ <p style="color: grey"> Python recipe 577997 by <a href="/recipes/users/4178764/">Giampaolo Rodolà</a> (<a href="/recipes/tags/atexit/">atexit</a>, <a href="/recipes/tags/contextlib/">contextlib</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/exit/">exit</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/shutdown/">shutdown</a>, <a href="/recipes/tags/sigint/">sigint</a>, <a href="/recipes/tags/signal/">signal</a>, <a href="/recipes/tags/sigterm/">sigterm</a>). Revision 23. </p> <p>A context manager which properly handles SIGTERM (SystemExit) and SIGINT (KeyboardInterrupt) signals, registering a function which is always guaranteed to be called on interpreter exit. Also, it makes sure to execute previously registered functions as well (if any).</p> CleanupManager for with statements (Python) 2011-12-18T07:20:46-08:00Nick Coghlanhttp://code.activestate.com/recipes/users/2035254/http://code.activestate.com/recipes/577981-cleanupmanager-for-with-statements/ <p style="color: grey"> Python recipe 577981 by <a href="/recipes/users/2035254/">Nick Coghlan</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>). Revision 5. </p> <p>Inspired by unittest.TestCase.addCleanup(), CleanupManager provides a means to programmatically add resources to be cleaned up when leaving a with statement. This makes it easy to use with optional resources, and those derived from sequences of inputs.</p> <p>An more powerful version of this recipe with a few additional features is published under the name <code>ContextStack</code> as part of the contextlib2 module: <a href="http://contextlib2.readthedocs.org" rel="nofollow">http://contextlib2.readthedocs.org</a></p> <p>This recipe is based on a suggestion originally posted by Nikolaus Rath at <a href="http://bugs.python.org/issue13585" rel="nofollow">http://bugs.python.org/issue13585</a></p> Context manager for low-level redirection of stdout/stderr (Python) 2012-01-26T02:14:25-08:00Greg Haskinshttp://code.activestate.com/recipes/users/4176881/http://code.activestate.com/recipes/577564-context-manager-for-low-level-redirection-of-stdou/ <p style="color: grey"> Python recipe 577564 by <a href="/recipes/users/4176881/">Greg Haskins</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/context_manager/">context_manager</a>, <a href="/recipes/tags/f2py/">f2py</a>, <a href="/recipes/tags/fortran/">fortran</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/redirect/">redirect</a>, <a href="/recipes/tags/stdout/">stdout</a>). Revision 3. </p> <p>This context manager provides a convenient, Pythonic way to temporarily replace the file descriptors of <code>stdout</code> and <code>stderr</code>, redirecting to either <code>os.devnull</code> or files of your choosing. Swapping the C-level file descriptors is required when suppressing output from compiled extension modules, such as those built using F2PY. It functions equally well for pure-Python code. <em>UPDATE:</em> (see below).</p> Decorator 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> POSIX context manager to temporarily silence, or filter lines from stdout (Python) 2010-03-03T06:17:23-08:00pwallerhttp://code.activestate.com/recipes/users/4173218/http://code.activestate.com/recipes/577083-posix-context-manager-to-temporarily-silence-or-fi/ <p style="color: grey"> Python recipe 577083 by <a href="/recipes/users/4173218/">pwaller</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/freopen/">freopen</a>, <a href="/recipes/tags/silence/">silence</a>, <a href="/recipes/tags/stdout/">stdout</a>, <a href="/recipes/tags/with/">with</a>). Revision 2. </p> <p>Fed up with libraries you don't have control over emitting text into your precious stdout?</p> <p>If they use stdout through python, then you can just change sys.stdout to be something else. If they are printing directly to stdout through a C module, or some other means, then you are stuck.</p> <p>.. at least until you discover the <code>with silence():</code> block!</p> <p>Caveats: Non-portable, tested only on 2.6 under Linux, uses threading.</p> <p>Example output:</p> <pre class="prettyprint"><code>$ python silence_file.py Before with block.. Sensible stuff! After the silence block </code></pre> Simple lock-queue via Memcached (Python) 2008-11-19T01:32:07-08:00Tal Einathttp://code.activestate.com/recipes/users/2892534/http://code.activestate.com/recipes/576567-simple-lock-queue-via-memcached/ <p style="color: grey"> Python recipe 576567 by <a href="/recipes/users/2892534/">Tal Einat</a> (<a href="/recipes/tags/concurrency/">concurrency</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/lock/">lock</a>, <a href="/recipes/tags/locking/">locking</a>, <a href="/recipes/tags/memcache/">memcache</a>, <a href="/recipes/tags/memcached/">memcached</a>, <a href="/recipes/tags/queue/">queue</a>). </p> <p>A simple lock-queue (FIFO) context manager implemented with <a href="http://www.danga.com/memcached/">Memcached</a>.</p> <p>In essence this is a normal lock, where the requests to acquire the lock are granted in the order in which they were originally made. Note that requests to acquire the lock are always blocking.</p>