Popular recipes tagged "decorator"http://code.activestate.com/recipes/tags/decorator/popular/2016-05-01T13:11:05-07:00ActiveState Code RecipesFunction guards for Python 3 (Python)
2016-05-01T13:11:05-07:00Dmitry Dvoinikovhttp://code.activestate.com/recipes/users/2475216/http://code.activestate.com/recipes/580658-function-guards-for-python-3/
<p style="color: grey">
Python
recipe 580658
by <a href="/recipes/users/2475216/">Dmitry Dvoinikov</a>
(<a href="/recipes/tags/call/">call</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/dispatch/">dispatch</a>, <a href="/recipes/tags/function/">function</a>, <a href="/recipes/tags/guard/">guard</a>).
</p>
<p>This module implements a function guard - facility to redirect the the call to one of several function implementations at run time based on the actual call arguments.</p>
<p>Wrap each of the identically named functions in a @guard decorator and provide a _when parameter with a default value set to guarding expression.</p>
<p>See samples at the top of the module.</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>
Decorator to check if needed modules for method are imported (Python)
2014-03-18T14:11:20-07:00Andrey Nikishaevhttp://code.activestate.com/recipes/users/4176176/http://code.activestate.com/recipes/578852-decorator-to-check-if-needed-modules-for-method-ar/
<p style="color: grey">
Python
recipe 578852
by <a href="/recipes/users/4176176/">Andrey Nikishaev</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/import/">import</a>).
</p>
<p>Check if needed modules imported before run method</p>
<pre class="prettyprint"><code>Example::
@require_module(['time'],exception=Exception)
def get_time():
return time.time()
</code></pre>
More strict unittests using a validator (Python)
2014-03-01T12:37:47-08:00Thomas Lehmannhttp://code.activestate.com/recipes/users/4174477/http://code.activestate.com/recipes/578793-more-strict-unittests-using-a-validator/
<p style="color: grey">
Python
recipe 578793
by <a href="/recipes/users/4174477/">Thomas Lehmann</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/unittests/">unittests</a>, <a href="/recipes/tags/validator/">validator</a>).
Revision 4.
</p>
<p>The main point is that <strong>there was no binding between a unit tests and the concrete class</strong>. It did happend often that you are indirectly testing a class using it also the concrete test class has missed some concrete test methods. I found this fact sometimes very irritating seeing 100% coverage.</p>
<p>Therefor I now provide this class decorator where you can specify the class that will be tested. If you do not specify test methods for each method of the testable class <strong>an exception will be thrown providing a list of missed tests</strong>.</p>
<p>Here some examples how it works: You implemented a</p>
<ul>
<li>method "__eq__", then write a "testEqual" method</li>
<li>method "__init__", then write a testInit" method</li>
<li>method "scalar_product", then write a testScalarProduct" method</li>
<li>and so on ...</li>
</ul>
<p>The way to use this class decorator you can see in the doctest area (see below in the code)
The only point to be aware of is that when you use the decorator you have to implement all test to get rid of the thrown execption. Of course you can implement more tests for same class.</p>
<p>New in revision 4 (1st march 2014):</p>
<ul>
<li>Bugfix: the algorithm were not correctly detecting which methods were really overwritten forcing to implement tests for methods which were base class only.</li>
<li>Bugfix: decorated classes which contain the attribute "decorated_object" can be handled properly. </li>
<li><p>A new second parameter now allows you to implement several classes in same test class forcing you to include the class name in the test method:</p>
<ul>
<li>@ValidateTestResponsibilityFor(Square, True)</li>
<li>@ValidateTestResponsibilityFor(Sin, True)</li>
<li>=> testSquareInit, testSquareGet, testSinInit, testSinGet, ...</li>
<li>This for smaller classes to avoid too many files (at least ... you decided)</li>
</ul></li>
</ul>
language decorator (Python)
2013-10-02T08:00:29-07:00Dr. Trigonhttp://code.activestate.com/recipes/users/4188033/http://code.activestate.com/recipes/578677-language-decorator/
<p style="color: grey">
Python
recipe 578677
by <a href="/recipes/users/4188033/">Dr. Trigon</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/embedded_language/">embedded_language</a>).
</p>
<p>Use other languages like lua, C++ or simple bash from python. Instead of writing code as a string and then send it to some eval or execute function, we introduce here decorators that allow to write regular python functions containing the external code as docstring.</p>
<p>That way the external code needs minimal adoptions only and becomes better read- and maintainable. Write your function in your favourite language and just place the right decorator in front of it - it simple like that.</p>
<p>At the current state this recipe is a DRAFT and needs to be further extended and tested.</p>
Humanize decorator (Python)
2013-07-31T16:04:13-07:00tomer filibahttp://code.activestate.com/recipes/users/2520014/http://code.activestate.com/recipes/578619-humanize-decorator/
<p style="color: grey">
Python
recipe 578619
by <a href="/recipes/users/2520014/">tomer filiba</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/objects/">objects</a>, <a href="/recipes/tags/pretty/">pretty</a>, <a href="/recipes/tags/print/">print</a>).
</p>
<p>When you need to inspect Python objects in a human-readable way, you're usually required to implement a custom <code>__str__</code> or <code>__repr__</code> which are just boilerplate (e.g., <code>return "Foo(%r, %r, %r)" % (self.bar, self.spam, self.eggs)</code>. You may implement <code>__str__</code> and <code>__repr__</code> by a base-class, but it's hard to call it <em>inheritance</em> and moreover, you may wish to remove it when you're done debugging.</p>
<p>This simple (yet complete) recipe is a class decorator that injects <code>__str__</code> and <code>__repr__</code> into the class being printed. It handles nesting and even cycle detection, allowing you to just plug it into existing classes to get them pretty-printed and perhaps remove it later.</p>
Inherit method docstrings without breaking decorators or violating DRY (Python)
2013-07-01T02:29:40-07:00nikratiohttp://code.activestate.com/recipes/users/4180248/http://code.activestate.com/recipes/578587-inherit-method-docstrings-without-breaking-decorat/
<p style="color: grey">
Python
recipe 578587
by <a href="/recipes/users/4180248/">nikratio</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/docstring/">docstring</a>, <a href="/recipes/tags/inheritance/">inheritance</a>).
Revision 2.
</p>
<p>There are several recipes for inheriting method docstrings. However, most of them either violate DRY (and have you repeat the ancestor class name in the method decorator that sets the docstring), or do break decorators that try to access the docstring (because the docstring is only assigned after class creation). This recipe avoids both problems.</p>
<p><strong>Note</strong>: This recipe uses the mro method from <a href="http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/" rel="nofollow">http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/</a></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>
Type checking using Python 3.x annotations (Python)
2013-05-23T22:46:19-07:00David Mertzhttp://code.activestate.com/recipes/users/4173018/http://code.activestate.com/recipes/578528-type-checking-using-python-3x-annotations/
<p style="color: grey">
Python
recipe 578528
by <a href="/recipes/users/4173018/">David Mertz</a>
(<a href="/recipes/tags/annotations/">annotations</a>, <a href="/recipes/tags/check/">check</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/type/">type</a>, <a href="/recipes/tags/typecheck/">typecheck</a>).
Revision 5.
</p>
<p>Some other recipes have been suggested to allow type checking by various means. Some of these require the use of type specification in a decorator itself. Others try to be much more elaborate in processing a large variety of annotations (but hence require much more and more convoluted code).</p>
<p>The recipe provided below is very short, and simply provides actual <strong>type</strong> checking of arguments and return values. It utilizes an unadorned decorator, rather than manufacture one that is parameterized by types or other arguments.</p>
Probably the fastest memoization decorator in the world (Python)
2012-08-02T07:27:12-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
<p style="color: grey">
Python
recipe 578231
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/cache/">cache</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/memo/">memo</a>, <a href="/recipes/tags/memoization/">memoization</a>).
</p>
<p>With apologies to a certain European brand of beer, this is probably the fastest memoization decorator in the world. Implemented using the __missing__ method in a dict subclass. </p>
Optional arguments decorator (Python)
2013-01-28T05:03:43-08:00Maxime H Lapointehttp://code.activestate.com/recipes/users/4185033/http://code.activestate.com/recipes/578435-optional-arguments-decorator/
<p style="color: grey">
Python
recipe 578435
by <a href="/recipes/users/4185033/">Maxime H Lapointe</a>
(<a href="/recipes/tags/class_decorator/">class_decorator</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/python/">python</a>).
Revision 2.
</p>
<p>If you need your decorator to receive arguments, optional or not, then you should decorate it with the opt_arg_dec decorator to handle all the logic that this implies for you.</p>
Immutable class decorator (Python)
2012-08-05T08:30:41-07:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/578233-immutable-class-decorator/
<p style="color: grey">
Python
recipe 578233
by <a href="/recipes/users/2033964/">Oren Tirosh</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/immutable/">immutable</a>).
</p>
<p>Apply this decorator to a class with __slots__. Members will be mutable during the execution of __init__ but read-only afterwards.</p>
A Python decorator that re-executes the function on condition (Python)
2012-07-24T09:51:48-07:00Chaobin Tang (唐超斌)http://code.activestate.com/recipes/users/4174076/http://code.activestate.com/recipes/578222-a-python-decorator-that-re-executes-the-function-o/
<p style="color: grey">
Python
recipe 578222
by <a href="/recipes/users/4174076/">Chaobin Tang (唐超斌)</a>
(<a href="/recipes/tags/closure/">closure</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/retry/">retry</a>).
Revision 3.
</p>
<p>Sometimes we want a function to be able to be retried automatically, such as a function that does networking trying to write/read data through a pre-established connection. Instead of writing try/except everywhere, a decorator would save much code and provide a single copy of code to do all the work.</p>
Recipe With No Name Yet (Python)
2012-08-22T17:57:12-07:00Cyrilhttp://code.activestate.com/recipes/users/4182937/http://code.activestate.com/recipes/578221-recipe-with-no-name-yet/
<p style="color: grey">
Python
recipe 578221
by <a href="/recipes/users/4182937/">Cyril</a>
(<a href="/recipes/tags/check/">check</a>, <a href="/recipes/tags/debug/">debug</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/wrapper/">wrapper</a>).
Revision 9.
</p>
<p>Not a very new recipe, but a short one and (I hope) useful :</p>
<ul>
<li>wrapping any function "f" with two decorators "enter_event" and "exit_event" that will trigger calling of user
functions when, ... hum ... evidently, <strong>just before entering and just after exiting the "f" function</strong>.</li>
</ul>
<p>Typical usages :</p>
<ul>
<li>debugging on a function by function basis :
<ul>
<li>emit a trace in log file to see when functions are called and check sequences correctness
(very usefull when programming by events)</li>
<li>feed a profile analyzer (by fine tuning which functions are enabled)</li>
<li>feed a code coverage analyzer ( " )</li>
</ul></li>
<li>kind of validator on function calling :
<ul>
<li>implement programming by contracts :
<ul>
<li>check that parameters values of "f" function will not have an unexpected value or be of an unexpected type</li>
<li>this allow to increase code robustness by narrowing </li>
</ul></li>
<li>implement invariants (eg. check that returned value is always in the excepted range, ...)</li>
<li>insure that a function follow specifications by meta-checking that has always predictable results
(eg. return the fixed expected value for each possible input value, ...)</li>
</ul></li>
<li>minimum modification of existing code</li>
<li><strong>in the same thinking line as the "monkey patching" concept</strong></li>
</ul>
<p>Notes on usage :</p>
<ul>
<li>recipe works on functions and any kind of methods (methods, class methods,
and static methods)</li>
<li>the usage order of "@enter_event" and "@exit_event" decorators doesn't
matter : the result will be the same</li>
</ul>
<ul>
<li><em>PLEASE VOTE FOR THIS RECIPE if you like it !</em></li>
</ul>
Recursively defined, Haskell-style infinite lists (Python)
2012-05-04T14:09:14-07:00John Crichtonhttp://code.activestate.com/recipes/users/4181975/http://code.activestate.com/recipes/578119-recursively-defined-haskell-style-infinite-lists/
<p style="color: grey">
Python
recipe 578119
by <a href="/recipes/users/4181975/">John Crichton</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/functional/">functional</a>, <a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/infinite/">infinite</a>, <a href="/recipes/tags/itertools/">itertools</a>, <a href="/recipes/tags/lazy/">lazy</a>, <a href="/recipes/tags/recursive/">recursive</a>).
Revision 2.
</p>
<p>A decorator to simplify the creation of recursively defined, Haskell-style infinite lists -- ie. recursive generators -- inspired by Raymond Hettinger's "Technique for cyclical iteration" [*]. </p>
<p>[*] <a href="http://code.activestate.com/recipes/576961-technique-for-cyclical-iteration/" rel="nofollow">http://code.activestate.com/recipes/576961-technique-for-cyclical-iteration/</a> </p>
Create and apply filters to lists of file paths (Python)
2012-03-20T21:17:26-07:00eysihttp://code.activestate.com/recipes/users/4177096/http://code.activestate.com/recipes/578084-create-and-apply-filters-to-lists-of-file-paths/
<p style="color: grey">
Python
recipe 578084
by <a href="/recipes/users/4177096/">eysi</a>
(<a href="/recipes/tags/blacklist/">blacklist</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/filter/">filter</a>, <a href="/recipes/tags/walk/">walk</a>, <a href="/recipes/tags/whitelist/">whitelist</a>, <a href="/recipes/tags/yield/">yield</a>).
Revision 2.
</p>
<p>An experiment with filtering lists of files, documentation is written directly into the code.</p>
Dynamic function parameters using annotations (Python)
2012-02-22T22:31:02-08:00pavelhttp://code.activestate.com/recipes/users/4171837/http://code.activestate.com/recipes/578049-dynamic-function-parameters-using-annotations/
<p style="color: grey">
Python
recipe 578049
by <a href="/recipes/users/4171837/">pavel</a>
(<a href="/recipes/tags/annotations/">annotations</a>, <a href="/recipes/tags/decorator/">decorator</a>).
</p>
<p>Python default values for keyword arguments are evaluated only once and not on every function call. For example following function will not work as user may expect:</p>
<pre class="prettyprint"><code>def printNow(l=[], now=datetime.now()):
l.append(len(l))
print('List:', l, ' id:', id(l))
print('Now:', now)
for i in range(3):
printNow()
print()
</code></pre>
<p>The "dynamic" decorator solves problem by evaluating callables, that are assigned to parameters using annotations syntax (see PEP 3107).</p>
RPDB (RobotPythonDebugger) -- a smarter way to debug robotframework tests (Python)
2012-03-14T15:12:39-07:00Daniel Cohnhttp://code.activestate.com/recipes/users/4172918/http://code.activestate.com/recipes/578073-rpdb-robotpythondebugger-a-smarter-way-to-debug-ro/
<p style="color: grey">
Python
recipe 578073
by <a href="/recipes/users/4172918/">Daniel Cohn</a>
(<a href="/recipes/tags/debugging/">debugging</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/pdb/">pdb</a>, <a href="/recipes/tags/redirect/">redirect</a>, <a href="/recipes/tags/robot/">robot</a>, <a href="/recipes/tags/rpdb/">rpdb</a>, <a href="/recipes/tags/stdin/">stdin</a>, <a href="/recipes/tags/stdout/">stdout</a>).
</p>
<p>Robotframework (<a href="http://code.google.com/p/robotframework/" rel="nofollow">http://code.google.com/p/robotframework/</a>) is a tool used to run functional tests against a variety of targets. Tests are organized in the form of keyword tsv or html files, which map input parameters to keyword-argument methods in the test suite. Robot includes a fairly advanced logging mechanism, which is cool -- until you try to debug anything. Debugging is made difficult because robot steals stdin and stdout when it is run, which means bye-bye debugging in the terminal. rpdb solves this in a KISS simple way.</p>