Popular recipes by Cyril http://code.activestate.com/recipes/users/4182937/2012-08-22T17:57:12-07:00ActiveState Code RecipesRecipe 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>