Top-rated recipes tagged "open"http://code.activestate.com/recipes/tags/open/top/2017-03-13T13:27:50-07:00ActiveState Code RecipesContext 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> Dynamically modifying class attributes at runtime (Python) 2011-03-31T20:07:18-07:00Nabil Stendardohttp://code.activestate.com/recipes/users/4177507/http://code.activestate.com/recipes/577628-dynamically-modifying-class-attributes-at-runtime/ <p style="color: grey"> Python recipe 577628 by <a href="/recipes/users/4177507/">Nabil Stendardo</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/modification/">modification</a>, <a href="/recipes/tags/monkeypatching/">monkeypatching</a>, <a href="/recipes/tags/open/">open</a>). </p> <p>However considered bad programming, Ruby/JavaScript-like open classes (i.e. classes which can be modified at runtime) actually can be a programming pattern when developing plug-in architectures. And, guess what, Python has that functionality too. This code allows to add attributes (typically methods) to classes, even when already instantiated.</p>