Top-rated Python recipes tagged "meta:requires=functools"http://code.activestate.com/recipes/langs/python/tags/meta:requires=functools/top/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>
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>
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>
Smarter Default Arguments (Python)
2011-08-12T23:06:57-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577786-smarter-default-arguments/
<p style="color: grey">
Python
recipe 577786
by <a href="/recipes/users/4177816/">Eric Snow</a>
(<a href="/recipes/tags/default_arguments/">default_arguments</a>, <a href="/recipes/tags/deferred/">deferred</a>, <a href="/recipes/tags/function/">function</a>, <a href="/recipes/tags/functions/">functions</a>).
Revision 3.
</p>
<p>Improved handling of mutable and deferred default arguments. After the recipe you'll find an explanation of what that means.</p>
<p>Works for 2.7 with minor tweaks (getfullargspec --> getargspec).</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>
Error logging with context manager and decorator (Python)
2007-09-19T06:52:58-07:00Kent Johnsonhttp://code.activestate.com/recipes/users/2016182/http://code.activestate.com/recipes/531821-error-logging-with-context-manager-and-decorator/
<p style="color: grey">
Python
recipe 531821
by <a href="/recipes/users/2016182/">Kent Johnson</a>
(<a href="/recipes/tags/shortcuts/">shortcuts</a>).
</p>
<p>A context manager and decorator that wrap common exception trapping and handling code so they may be applied with just a single line of code in the client.</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>
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>
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>
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>
Pick random elements from a predefined list of choices (Python)
2011-06-14T17:46:41-07:00Patrick Dobbshttp://code.activestate.com/recipes/users/4177984/http://code.activestate.com/recipes/577754-pick-random-elements-from-a-predefined-list-of-cho/
<p style="color: grey">
Python
recipe 577754
by <a href="/recipes/users/4177984/">Patrick Dobbs</a>
(<a href="/recipes/tags/choice/">choice</a>, <a href="/recipes/tags/random/">random</a>, <a href="/recipes/tags/selection/">selection</a>).
</p>
<p>This (quick but strangely satisfying) recipe combines the use of random.choice with functools.partial from the standard library. It is a factory function returning random.choice pre-filled with its sequence of options.</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>
dualmethod descriptor (Python)
2010-02-06T20:54:45-08:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/577030-dualmethod-descriptor/
<p style="color: grey">
Python
recipe 577030
by <a href="/recipes/users/4172944/">Steven D'Aprano</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/method/">method</a>).
Revision 3.
</p>
<p>This descriptor can be used to decorate methods, similar to the built-ins classmethod and staticmethod. It enables the caller to call methods on either the class or an instance, and the first argument passed to the method will be the class or the instance respectively.</p>
<p>This differs from classmethods, which always passes the class, and staticmethods, which don't pass either.</p>
<p>Like all descriptors, you can only use this in new-style classes.</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>
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>
typeparser (Python)
2007-04-15T04:24:53-07:00Florian Leitnerhttp://code.activestate.com/recipes/users/4049249/http://code.activestate.com/recipes/511473-typeparser/
<p style="color: grey">
Python
recipe 511473
by <a href="/recipes/users/4049249/">Florian Leitner</a>
(<a href="/recipes/tags/algorithms/">algorithms</a>).
Revision 2.
</p>
<p>Python type-string parser. The code evolved from a post in python-list on 11/22/05 by Fredrik Lundh on a dictionary parser. It parses a type-string to their type objects for all basic types. Raises SyntaxError and SemanticError on failures.</p>
<p>Supported types:
* containers: defaultdict, deque, dict, list, tuple, set
* basic types: Decimal, bool, float, int, long, str
* None type</p>
<p>REQUIRES PYTHON >= 2.5</p>