Most viewed recipes tagged "meta:requires=functools"http://code.activestate.com/recipes/tags/meta:requires=functools/views/2017-06-25T17:17:43-07:00ActiveState Code RecipesLRU and LFU cache decorators (Python) 2010-08-01T01:19:23-07:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/ <p style="color: grey"> Python recipe 498245 by <a href="/recipes/users/178123/">Raymond Hettinger</a> (<a href="/recipes/tags/shortcuts/">shortcuts</a>). Revision 6. </p> <p>One-line decorator call adds caching to functions with hashable arguments and no keyword arguments. When the maximum size is reached, the least recently used entry or least frequently used entry is discarded -- appropriate for long-running processes which cannot allow caches to grow without bound. Includes built-in performance instrumentation.</p> Guard against an exception in the wrong place (Python) 2017-06-25T17:17:43-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/580808-guard-against-an-exception-in-the-wrong-place/ <p style="color: grey"> Python recipe 580808 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/context/">context</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/guard/">guard</a>, <a href="/recipes/tags/manager/">manager</a>). Revision 2. </p> <p>Sometimes exception handling can obscure bugs unless you guard against a particular exception occurring in a certain place. One example is that <a href="https://www.python.org/dev/peps/pep-0479/">accidentally raising <code>StopIteration</code> inside a generator</a> will halt the generator instead of displaying a traceback. That was solved by PEP 479, which automatically has such <code>StopIteration</code> exceptions change to <code>RuntimeError</code>. See the discussion below for further examples.</p> <p>Here is a class which can be used as either a decorator or context manager for guarding against the given exceptions. It takes an exception (or a tuple of exceptions) as argument, and if the wrapped code raises that exception, it is re-raised as another exception type (by default <code>RuntimeError</code>).</p> <p>For example:</p> <pre class="prettyprint"><code>try: with exception_guard(ZeroDivisionError): 1/0 # raises ZeroDivisionError except RuntimeError: print ('ZeroDivisionError replaced by RuntimeError') @exception_guard(KeyError) def demo(): return {}['key'] # raises KeyError try: demo() except RuntimeError: print ('KeyError replaced by RuntimeError') </code></pre> A memoize decorator for instance methods (Python) 2010-11-04T20:23:35-07:00Daniel Millerhttp://code.activestate.com/recipes/users/4016391/http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ <p style="color: grey"> Python recipe 577452 by <a href="/recipes/users/4016391/">Daniel Miller</a> (<a href="/recipes/tags/cache/">cache</a>, <a href="/recipes/tags/functools/">functools</a>, <a href="/recipes/tags/memoize/">memoize</a>, <a href="/recipes/tags/partial/">partial</a>). </p> <p>A simple result-caching decorator for instance methods. NOTE: does not work with plain old non-instance-method functions. The cache is stored on the instance to prevent memory leaks caused by long-term caching beyond the life of the instance (almost all other recipes I found suffer from this problem when used with instance methods).</p> Py2.6+ and Py3.0+ backport of Python 3.3's LRU Cache (Python) 2013-03-06T05:38:15-08:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/ <p style="color: grey"> Python recipe 578078 by <a href="/recipes/users/178123/">Raymond Hettinger</a> (<a href="/recipes/tags/cache/">cache</a>, <a href="/recipes/tags/lru/">lru</a>). Revision 6. </p> <p>Full-featured O(1) LRU cache backported from Python3.3. The full Py3.3 API is supported (thread safety, maxsize, keyword args, type checking, __wrapped__, and cache_info). Includes Py3.3 optimizations for better memory utilization, fewer dependencies, and fewer dict lookups.</p> Finding the percentile of the values (Python) 2011-04-25T03:41:08-07:00Wai Yip Tunghttp://code.activestate.com/recipes/users/2382677/http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/ <p style="color: grey"> Python recipe 511478 by <a href="/recipes/users/2382677/">Wai Yip Tung</a> (<a href="/recipes/tags/algorithms/">algorithms</a>). Revision 2. </p> <p>This function find the percentile of a list of values. Note that the list must be sorted already.</p> Python reader + writer for spss sav files (Linux, Mac & Windows) (Python) 2013-02-20T22:07:27-08:00Albert-Jan Roskamhttp://code.activestate.com/recipes/users/4177640/http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/ <p style="color: grey"> Python recipe 577811 by <a href="/recipes/users/4177640/">Albert-Jan Roskam</a> (<a href="/recipes/tags/reader/">reader</a>, <a href="/recipes/tags/sav/">sav</a>, <a href="/recipes/tags/spss/">spss</a>, <a href="/recipes/tags/writer/">writer</a>). Revision 12. </p> <p><strong>Python Program to READ &amp; WRITE Spss system files (.sav) (Linux,Mac or Windows)</strong></p> <ul> <li><em>Check <a href="https://pypi.python.org/pypi/savReaderWriter/" rel="nofollow">https://pypi.python.org/pypi/savReaderWriter/</a> for the latest version (including the libraries!)</em></li> <li>Requires libspssdio.so.1 (LINUX) or libspssdio.dylib (MAC) or spssio32.dll (WINDOWS) plus associated libaries, which can be freely downloaded from: <a href="https://www.ibm.com/developerworks/mydeveloperworks/wikis/home/wiki/We70df3195ec8_4f95_9773_42e448fa9029/page/Downloads%2520for%2520IBM%25C2%25AE%2520SPSS%25C2%25AE%2520Statistics?lang=en" rel="nofollow">https://www.ibm.com/developerworks/mydeveloperworks/wikis/home/wiki/We70df3195ec8_4f95_9773_42e448fa9029/page/Downloads%20for%20IBM%C2%AE%20SPSS%C2%AE%20Statistics?lang=en</a></li> <li>It is recommended to download the v21 I/O files (required for writing zlib (.zsav) compressed files)</li> <li>December 2012 (complete rewrite):</li> <li>Added support for slicing, indexing, array slicing + other special methods</li> <li>Added support for writing spss date fields</li> <li>Added support for almost all meta data (missing values, sets, roles, etc.)</li> <li>Added support for 64 bit Windows (tested with Win7) and other OSs (z/Linux, Solaris, HP Linux, IBM AIX (untested though)</li> <li>Added support for reading and writing zlib compressed (.zsav) files</li> <li>Removed pesky segfault error when freeing memory</li> <li>Removed errors related to encoding</li> <li>Changed some Reader defaults (verbose=False, returnHeader=False)</li> <li>Renamed SavDataDictionaryReader into SavHeaderReader</li> </ul> <p><strong>LINUX:</strong></p> <p><em>Installation (tested on Linux Ubuntu 10):</em></p> <ul> <li>additional packages/files needed are: intel-icc8-libs_8.0-1_i386.deb,libicu32_3.2-3_i386.deb, libstdc++5_3.3.6-20_i386.deb, libirc.so.</li> <li>Run the following commands in your terminal: sudo apt-get install intel-icc8-libs; sudo apt-get install libicu32; sudo apt-get install libstdc++5.</li> <li>Then convert libirc.a (static) to libirc.so (dynamic), save in same location as libspssdio.so.1: ar vx intel-icc8-libs_8.0-1_i386.deb; tar -xzvf data.tar.gz ./usr/lib/libirc.a; ar -x libirc.a.</li> </ul> <p><em>Calling the program:</em></p> <ul> <li>In the TERMINAL type: export LD_LIBRARY_PATH=/path/of/additional/sofiles; python /some/path/wrapperToProgram.py. You may also add ld_library_path to .bashrc</li> <li>The wrapper starts with "from SavReaderWriter import *", followed by e.g. stuff from the if __name__ == '__main__' section</li> </ul> <p><strong>MAC OS:</strong></p> <ul> <li>you must put all the dylib files that come with the IBM SPSS_Statistics_InputOutput_Modules_* package in the macos directory somewhere that OS X can find them</li> <li>one simple way to accomplish this is to copy them to /usr/lib</li> </ul> <p><strong>WINDOWS:</strong></p> <ul> <li>You can also find this dll in the installation directory of SPSS (although SPSS is _not_ needed!)</li> <li>The .dll should be saved in the same location as this program.</li> </ul> <p><strong>USAGE:</strong> See docstrings + __main__ section</p> Simple threading decorator (Python) 2009-03-10T01:38:51-07:00david.gaarenstroomhttp://code.activestate.com/recipes/users/4168848/http://code.activestate.com/recipes/576684-simple-threading-decorator/ <p style="color: grey"> Python recipe 576684 by <a href="/recipes/users/4168848/">david.gaarenstroom</a> (<a href="/recipes/tags/async/">async</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/run_asynchronously/">run_asynchronously</a>, <a href="/recipes/tags/thread/">thread</a>, <a href="/recipes/tags/threading/">threading</a>). Revision 4. </p> <p>When you're new at threading, using threads can be a bit daunting at first. If all you want is just to "run this function in parallel (= asynchronously) to the main program code", then this recipe can be of use. Simply use "@run_async" as a decorator for the function you want to run asynchronously. A call to that function will return immediately but the function itself will run in parallel.</p> Simple caching decorator (Python) 2010-12-01T00:43:01-08:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/577479-simple-caching-decorator/ <p style="color: grey"> Python recipe 577479 by <a href="/recipes/users/178123/">Raymond Hettinger</a> (<a href="/recipes/tags/cache/">cache</a>, <a href="/recipes/tags/memoization/">memoization</a>). </p> <p>Memoizing decorator. Has the same API as the functools.lru_cache() in Py3.2 but without the LRU feature, so it takes less memory, runs faster, and doesn't need locks to keep the dictionary in a consistent state.</p> Method signature type checking decorator for Python 3 (Python) 2015-05-15T09:25:08-07:00Dmitry Dvoinikovhttp://code.activestate.com/recipes/users/2475216/http://code.activestate.com/recipes/572161-method-signature-type-checking-decorator-for-pytho/ <p style="color: grey"> Python recipe 572161 by <a href="/recipes/users/2475216/">Dmitry Dvoinikov</a> (<a href="/recipes/tags/checking/">checking</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/interface/">interface</a>, <a href="/recipes/tags/method/">method</a>, <a href="/recipes/tags/signature/">signature</a>, <a href="/recipes/tags/sysadmin/">sysadmin</a>, <a href="/recipes/tags/type/">type</a>). Revision 8. </p> <p>This recipe allows nice and clean validation for method parameters/return values. It uses function annotations available in Python 3 for the actual signature specification.</p> namedtuple.abc - abstract base class + mix-in for named tuples (Python) 2011-04-02T02:07:00-07:00Jan Kaliszewskihttp://code.activestate.com/recipes/users/4172762/http://code.activestate.com/recipes/577629-namedtupleabc-abstract-base-class-mix-in-for-named/ <p style="color: grey"> Python recipe 577629 by <a href="/recipes/users/4172762/">Jan Kaliszewski</a> (<a href="/recipes/tags/abc/">abc</a>, <a href="/recipes/tags/collections/">collections</a>, <a href="/recipes/tags/dry/">dry</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/namedtuple/">namedtuple</a>, <a href="/recipes/tags/shortcuts/">shortcuts</a>). Revision 7. </p> <p>If you need</p> <ul> <li>to define <strong>named tuple subclasses</strong> (including reusable abstract ones), adding/overriding some methods, in a convenient way;</li> <li>to have the named tuple ABC (abstract base class) for <strong>isinstance/issubclass</strong> tests;</li> <li>or simply would like to define your named tuple classes in a <strong>class-syntax-based and DRY way</strong> (without repeating type names...)</li> </ul> <p>-- <strong>this recipe is for you.</strong></p> Trace decorator for debugging (Python) 2011-01-24T18:40:51-08:00Kevin L. Sitzehttp://code.activestate.com/recipes/users/4173535/http://code.activestate.com/recipes/577551-trace-decorator-for-debugging/ <p style="color: grey"> Python recipe 577551 by <a href="/recipes/users/4173535/">Kevin L. Sitze</a> (<a href="/recipes/tags/classes/">classes</a>, <a href="/recipes/tags/debug/">debug</a>, <a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/functions/">functions</a>, <a href="/recipes/tags/inspection/">inspection</a>, <a href="/recipes/tags/modules/">modules</a>, <a href="/recipes/tags/trace/">trace</a>). Revision 2. </p> <p>This package provides a decorator for tracing function and method calls in your applications. The tracing capabilities are managed through the logging package, and several mechanisms are provided for controlling the destination of the trace output.</p> <p>It also provides functionality for adding decorators to existing classes or modules.</p> Longest common subsequence problem solver (Python) 2009-08-06T06:36:56-07:00Shao-chuan Wanghttp://code.activestate.com/recipes/users/4168519/http://code.activestate.com/recipes/576869-longest-common-subsequence-problem-solver/ <p style="color: grey"> Python recipe 576869 by <a href="/recipes/users/4168519/">Shao-chuan Wang</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/lcs/">lcs</a>, <a href="/recipes/tags/longest_common_subsequence/">longest_common_subsequence</a>). Revision 2. </p> <p>Longest common subsequence problem is a good example of dynamic programming, and also has its significance in biological applications.</p> <p>For more information about LCS, please see: <a href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem" rel="nofollow">http://en.wikipedia.org/wiki/Longest_common_subsequence_problem</a></p> <p>Also, here, I use a 'cached' decorator to keep core algorithm neat. You can see how great the decorator could be. :)</p> <p>Also note that, this recipe is just a demonstration of LCS and the usage of a python decorator. However, the memory is not used very efficiently. If the problem is very large-scaled, it may lead to stack overflow or memory error. </p> <p>So, do not use this recipe to deal with large-scaled problems. ;)</p> Docstring inheritance decorator (Python) 2009-07-28T13:42:32-07:00Shai Bergerhttp://code.activestate.com/recipes/users/2014324/http://code.activestate.com/recipes/576862-docstring-inheritance-decorator/ <p style="color: grey"> Python recipe 576862 by <a href="/recipes/users/2014324/">Shai Berger</a> (<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/docstring/">docstring</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/metaprogramming/">metaprogramming</a>). </p> <p>In many cases, a subclass overrides a method in a parent class, just to change its implementation; in such cases, it would be nice to preserve the overridden method's docstring. The decorator below can be used to achieve this without explicit reference to the parent class. It does this by replacing the function with a descriptor, which accesses the parent class when the method is accessed as an attribute.</p> GAE User Session with HTTP Basic Authentication (Python) 2010-05-20T23:49:49-07:00Berendhttp://code.activestate.com/recipes/users/4173891/http://code.activestate.com/recipes/577235-gae-user-session-with-http-basic-authentication/ <p style="color: grey"> Python recipe 577235 by <a href="/recipes/users/4173891/">Berend</a> (<a href="/recipes/tags/appengine/">appengine</a>, <a href="/recipes/tags/appspot/">appspot</a>, <a href="/recipes/tags/authentication/">authentication</a>, <a href="/recipes/tags/clients/">clients</a>, <a href="/recipes/tags/gae/">gae</a>, <a href="/recipes/tags/google/">google</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/sessions/">sessions</a>, <a href="/recipes/tags/web/">web</a>, <a href="/recipes/tags/wsgi/">wsgi</a>). Revision 6. </p> <p>HTTP Basic is an unsecure but easy to implement authentication protocol. I think its good enough for a simple client in front of an SSL capable server. Google App-Engine supports SSL, and here is a recipe to set up the user-session using HTTP Basic. </p> <p>gauth has the code from my not-really-a-recipe listing at: <a href="http://code.activestate.com/recipes/577217-routines-for-programmatically-authenticating-with-" rel="nofollow">http://code.activestate.com/recipes/577217-routines-for-programmatically-authenticating-with-</a></p> Topological Sort (Python) 2012-09-27T12:21:23-07:00Sam Dentonhttp://code.activestate.com/recipes/users/4172262/http://code.activestate.com/recipes/578272-topological-sort/ <p style="color: grey"> Python recipe 578272 by <a href="/recipes/users/4172262/">Sam Denton</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/sort/">sort</a>, <a href="/recipes/tags/sorting/">sorting</a>, <a href="/recipes/tags/topological/">topological</a>, <a href="/recipes/tags/toposort/">toposort</a>). </p> <p>A topological sort (sometimes abbreviated topsort or toposort) or topological ordering of a directed graph is a linear ordering of its vertices such that, for every edge uv, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG).</p> MineSweep (Python) 2010-09-16T14:45:36-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/577365-minesweep/ <p style="color: grey"> Python recipe 577365 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/game/">game</a>, <a href="/recipes/tags/minesweep/">minesweep</a>, <a href="/recipes/tags/python/">python</a>). Revision 2. </p> <p>A friend was wondering how to implement MineSweep and decided to try making the game in Excel. Unfortunately, the game was not quite as interactive as he wanted; and he is unable to get around certain limitations at the moment since he is still new to programming. To show off the power of Python and demonstrate how easy it can be to develop a simple demonstration program in the language, the following program (and its iterations) were put together between the hours of 1 and 6 in the morning. It could certainly be much better in its implementation, but any serious work were to be put into MineSweep, starting over from scratch would be the best choice (especially with interface design).</p> Search sequences for sub-sequence (Python) 2011-08-19T05:17:00-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577850-search-sequences-for-sub-sequence/ <p style="color: grey"> Python recipe 577850 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/find/">find</a>, <a href="/recipes/tags/searching/">searching</a>, <a href="/recipes/tags/sequence/">sequence</a>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/sublist/">sublist</a>, <a href="/recipes/tags/substring/">substring</a>). </p> <p>The list and tuple index() method and <code>in</code> operator test for element containment, unlike similar tests for strings, which checks for sub-strings:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; "12" in "0123" True &gt;&gt;&gt; [1, 2] in [0, 1, 2, 3] False </code></pre> <p>These two functions, search and rsearch, act like str.find() except they operate on any arbitrary sequence such as lists:</p> <pre class="prettyprint"><code>&gt;&gt;&gt; search([1, "a", "b", 2, 3], ["b", 2]) 2 </code></pre> Topological Sort (Python) 2010-09-28T19:22:27-07:00Paddy McCarthyhttp://code.activestate.com/recipes/users/398009/http://code.activestate.com/recipes/577413-topological-sort/ <p style="color: grey"> Python recipe 577413 by <a href="/recipes/users/398009/">Paddy McCarthy</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/sorting/">sorting</a>, <a href="/recipes/tags/topological/">topological</a>). </p> <p>Given items that depend on other items, a topological sort arranges items in order that no one item precedes an item it depends on. In this example items are strings and dependencies are expressed in a dictionary whose keys are items and whose values are a set of dependent items. Note that the dict may contain self-dependencies (which are ignored), and dependent items that are not also dict keys, such as the item 'ieee'.</p> Synchronization Decorator for Class Methods (Python) 2010-03-13T10:11:07-08:00Rodney Drenthhttp://code.activestate.com/recipes/users/4050661/http://code.activestate.com/recipes/577105-synchronization-decorator-for-class-methods/ <p style="color: grey"> Python recipe 577105 by <a href="/recipes/users/4050661/">Rodney Drenth</a> (<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/synchronize/">synchronize</a>, <a href="/recipes/tags/threads/">threads</a>). </p> <p>Synchronizes access to methods of a class with either an instance or class specific lock.</p> Implementing the observer pattern yet again: this time with coroutines and the with statement (Python) 2006-11-10T16:38:01-08:00Jim Bakerhttp://code.activestate.com/recipes/users/2810167/http://code.activestate.com/recipes/498259-implementing-the-observer-pattern-yet-again-this-t/ <p style="color: grey"> Python recipe 498259 by <a href="/recipes/users/2810167/">Jim Baker</a> (<a href="/recipes/tags/oop/">oop</a>). </p> <p>Implements the observer design pattern via generator coroutines, wrapped up to use the new 'with' statement of Python 2.5. Enables the loosely-coupled observation of any container implementing the dictionary protocol.</p>