Popular Python recipes tagged "meta:requires=functools"http://code.activestate.com/recipes/langs/python/tags/meta:requires=functools/2017-06-25T17:17:43-07:00ActiveState Code RecipesGuard 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>
Python2 keyword-only argument emulation as a decorator. Python3 compatible. (Python)
2016-04-15T13:25:20-07:00István Pásztorhttp://code.activestate.com/recipes/users/4189380/http://code.activestate.com/recipes/580639-python2-keyword-only-argument-emulation-as-a-decor/
<p style="color: grey">
Python
recipe 580639
by <a href="/recipes/users/4189380/">István Pásztor</a>
(<a href="/recipes/tags/args/">args</a>, <a href="/recipes/tags/arguments/">arguments</a>, <a href="/recipes/tags/keyword/">keyword</a>, <a href="/recipes/tags/keyword_only/">keyword_only</a>, <a href="/recipes/tags/kwonly/">kwonly</a>, <a href="/recipes/tags/only/">only</a>, <a href="/recipes/tags/python2/">python2</a>).
Revision 4.
</p>
<p>Provides a very simple decorator (~40 lines of code) that can turn some or all of your default arguments into keyword-only arguments. You select one of your default arguments by name and the decorator turn this argument along with all default arguments on its right side into keyword only arguments. Check the docstring of the decorator or visit the github/pypi page for detailed documentation:</p>
<ul>
<li><a href="https://github.com/pasztorpisti/kwonly-args" rel="nofollow">https://github.com/pasztorpisti/kwonly-args</a></li>
<li><a href="https://pypi.python.org/pypi/kwonly-args" rel="nofollow">https://pypi.python.org/pypi/kwonly-args</a></li>
</ul>
<p><code>$ pip install kwonly-args</code></p>
Decorator for defining functions with keyword-only arguments (Python)
2015-07-10T15:25:04-07:00Oscar Byrnehttp://code.activestate.com/recipes/users/4192487/http://code.activestate.com/recipes/579079-decorator-for-defining-functions-with-keyword-only/
<p style="color: grey">
Python
recipe 579079
by <a href="/recipes/users/4192487/">Oscar Byrne</a>
(<a href="/recipes/tags/arguments/">arguments</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/keyword/">keyword</a>, <a href="/recipes/tags/metadecorator/">metadecorator</a>, <a href="/recipes/tags/positional/">positional</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/python3/">python3</a>).
Revision 2.
</p>
<p>Python2.x implementation of python3's keyword-only arguments (aka arguments that must be specified as keywords, and are not automatically filled in by positional arguments - see PEP 3102).</p>
Fluent API method decorator (Python)
2015-07-08T13:20:58-07:00Oscar Byrnehttp://code.activestate.com/recipes/users/4192487/http://code.activestate.com/recipes/579078-fluent-api-method-decorator/
<p style="color: grey">
Python
recipe 579078
by <a href="/recipes/users/4192487/">Oscar Byrne</a>
(<a href="/recipes/tags/api/">api</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/fluent/">fluent</a>, <a href="/recipes/tags/interface/">interface</a>).
</p>
<p>A decorator for producing robust fluent API interfaces by returning a copy of self</p>
Keyword-only arguments in Python 2.x (Python)
2015-09-22T18:16:40-07:00Carahttp://code.activestate.com/recipes/users/4191397/http://code.activestate.com/recipes/578993-keyword-only-arguments-in-python-2x/
<p style="color: grey">
Python
recipe 578993
by <a href="/recipes/users/4191397/">Cara</a>
(<a href="/recipes/tags/arguments/">arguments</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/keyword/">keyword</a>, <a href="/recipes/tags/keyword_only/">keyword_only</a>).
Revision 10.
</p>
<p>This is a decorator that makes some of a function's or method's arguments into keyword-only arguments. As much as it possible, it emulates the Python 3 handling of keyword-only arguments, including messages for TypeErrors. It's compatible with Python 3 so it can be used in code bases that support both versions.</p>
Create on-the-fly class adapters with functools.partial (Python)
2014-05-29T18:48:28-07:00Christoph Schuelerhttp://code.activestate.com/recipes/users/4174094/http://code.activestate.com/recipes/578884-create-on-the-fly-class-adapters-with-functoolspar/
<p style="color: grey">
Python
recipe 578884
by <a href="/recipes/users/4174094/">Christoph Schueler</a>
(<a href="/recipes/tags/adapter/">adapter</a>, <a href="/recipes/tags/namedtuple/">namedtuple</a>, <a href="/recipes/tags/partial/">partial</a>, <a href="/recipes/tags/pattern/">pattern</a>).
</p>
<p>functools.partial could not only applied to functions it also works with classes.
This opens some interesting perspectives, like on-the-fly creation of class
adapters, as the following code illustrates.</p>
lru_timestamp - cache entry aging for functools.lru_cache (Python)
2014-02-02T21:28:25-08:00Peter Santorohttp://code.activestate.com/recipes/users/4189027/http://code.activestate.com/recipes/578817-lru_timestamp-cache-entry-aging-for-functoolslru_c/
<p style="color: grey">
Python
recipe 578817
by <a href="/recipes/users/4189027/">Peter Santoro</a>
(<a href="/recipes/tags/age/">age</a>, <a href="/recipes/tags/lru_cache/">lru_cache</a>).
</p>
<p>Return a timestamp string for @lru_cache decorated functions.</p>
<p>The returned timestamp is used as the value of an extra parameter
to @lru_cache decorated functions, allowing for more control over
how often cache entries are refreshed. The lru_timestamp function
should be called with the same refresh_interval value for a given
@lru_cache decorated function. The returned timestamp is for the
benefit of the @lru_cache decorator and is normally not used by
the decorated function.</p>
<p>Positional arguments:
refresh_interval -- in minutes (default 60), values less than 1
are coerced to 1, values more than 1440 are
coerced to 1440</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>
Pretty and Stated HTMLParsers (Python)
2013-12-14T00:28:36-08:00Ádám Szieberthhttp://code.activestate.com/recipes/users/4188745/http://code.activestate.com/recipes/578787-pretty-and-stated-htmlparsers/
<p style="color: grey">
Python
recipe 578787
by <a href="/recipes/users/4188745/">Ádám Szieberth</a>
(<a href="/recipes/tags/html/">html</a>, <a href="/recipes/tags/htmlparser/">htmlparser</a>, <a href="/recipes/tags/state/">state</a>).
Revision 2.
</p>
<p>Extensions of html.parser.HTMLParser().</p>
<p>PrettyHTMLParser() does not splits data into chuncks by HTML entities.
StatedHTMLParser() can have many state-dependent handlers which helps parsing HTML pages alot.</p>
PyQt4 pressed modifier keys names as method argument by a decorator (Python)
2013-09-29T14:13:04-07:00TNThttp://code.activestate.com/recipes/users/4187961/http://code.activestate.com/recipes/578675-pyqt4-pressed-modifier-keys-names-as-method-argume/
<p style="color: grey">
Python
recipe 578675
by <a href="/recipes/users/4187961/">TNT</a>
(<a href="/recipes/tags/keys/">keys</a>, <a href="/recipes/tags/modifier/">modifier</a>, <a href="/recipes/tags/pyqt/">pyqt</a>).
Revision 2.
</p>
<p>This is a definition of a decorator function that checks which modifier keys are being pressed and adds a keyword argument to a method. This argument is a tuple of names (strings) of the modifier keys that have been pressed when the method was called (or triggered).</p>
deprecate decorator which accepts arguments (Python)
2013-08-23T13:24:40-07:00tlatsashttp://code.activestate.com/recipes/users/4187618/http://code.activestate.com/recipes/578650-deprecate-decorator-which-accepts-arguments/
<p style="color: grey">
Python
recipe 578650
by <a href="/recipes/users/4187618/">tlatsas</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/deprecated/">deprecated</a>).
Revision 2.
</p>
<p>The deprecate decorator can be used to warn for future or current code deprecations. It accepts a message and an optional Warning class which will be passed to the warnings.warn() function.</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>
An analogue of enumerate for nested lists. (Python)
2012-12-11T16:59:14-08:00John Crichtonhttp://code.activestate.com/recipes/users/4181975/http://code.activestate.com/recipes/578376-an-analogue-of-enumerate-for-nested-lists/
<p style="color: grey">
Python
recipe 578376
by <a href="/recipes/users/4181975/">John Crichton</a>
(<a href="/recipes/tags/enumerate/">enumerate</a>, <a href="/recipes/tags/index/">index</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/list/">list</a>).
Revision 6.
</p>
<p>A generator function which enables traversal and modification of deeply nested lists. Together with the supplied helper functions it could be useful when working with data stored in deeply
nested lists, particularly when the level of nesting precludes a recursive approach.</p>
type Checking in Python using decorators (version 2.0) (Python)
2012-11-19T13:15:35-08:00LL Snarkhttp://code.activestate.com/recipes/users/4180463/http://code.activestate.com/recipes/578330-type-checking-in-python-using-decorators-version-2/
<p style="color: grey">
Python
recipe 578330
by <a href="/recipes/users/4180463/">LL Snark</a>
(<a href="/recipes/tags/checking/">checking</a>, <a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/type/">type</a>).
Revision 2.
</p>
<p>The two decorators checkparams and checkreturn allow you to check (at execution time) that function parameters or a function return value are the right type.</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 & 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>
DoubleDict (Python)
2012-07-24T21:24:14-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578224-doubledict/
<p style="color: grey">
Python
recipe 578224
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>).
</p>
<p>After seeing requests for being able to access keys in a dictionary by value, the following recipe was born. It creates the <code>DoubleDict</code> class and allows just that. To ensure that only one key is returned when accessing it by value, values must be unique just as keys are unique, and this rule is automatically enforced. Most dictionary methods are supported, and many more are added to allow working with the dictionary from the view of the values instead of the keys. Several optional metaclasses are also provided to enable optional features in the <code>DoubleDict</code> class such as data consistency checks and atomic method execution.</p>
threadbox.py (Python)
2012-10-09T22:40:09-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578152-threadboxpy/
<p style="color: grey">
Python
recipe 578152
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/threading/">threading</a>).
Revision 2.
</p>
<p>Provide a way to run instance methods on a single thread.</p>
<p>This module allows hierarchical classes to be cloned so that their instances
run on one thread. Method calls are automatically routed through a special
execution engine. This is helpful when building thread-safe GUI code.</p>
Cached Class (Python)
2012-01-06T02:24:08-08:00Peter Donishttp://code.activestate.com/recipes/users/4180313/http://code.activestate.com/recipes/577998-cached-class/
<p style="color: grey">
Python
recipe 577998
by <a href="/recipes/users/4180313/">Peter Donis</a>
(<a href="/recipes/tags/cache/">cache</a>, <a href="/recipes/tags/decorators/">decorators</a>).
Revision 5.
</p>
<p>A class decorator that ensures that only one instance of
the class exists for each distinct set of constructor
arguments.</p>
<p>Note that if a decorated class is subclassed, each subclass is cached separately. (This is because each cached subclass is a different <code>cls</code> argument to the <code>__new__</code> method.)</p>
vector (Python)
2012-01-09T05:35:39-08:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578006-vector/
<p style="color: grey">
Python
recipe 578006
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/datastructures/">datastructures</a>, <a href="/recipes/tags/library/">library</a>, <a href="/recipes/tags/utility/">utility</a>).
</p>
<p>Needed by <a href="http://code.activestate.com/recipes/578004/">recipe 578004</a>, this is meant to be a power pure-python-based module for running optimized 2D vector operations with a few possibilities not seen in most vector libraries. Many of the methods are overloaded to provide great versitility in what operations can be performed. To allow for even greater operations, the many methods mays be wrapped with the included <code>autocast</code> method so that even more datatypes can be used in whatever calculations the programmer may desire.</p>