Popular recipes tagged "annotations" but not "type"http://code.activestate.com/recipes/tags/annotations-type/2012-02-22T22:31:02-08:00ActiveState Code RecipesDynamic 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> Reevaluate functions when called, v3 (Python) 2009-05-14T15:18:41-07:00geremy condrahttp://code.activestate.com/recipes/users/4170000/http://code.activestate.com/recipes/576754-reevaluate-functions-when-called-v3/ <p style="color: grey"> Python recipe 576754 by <a href="/recipes/users/4170000/">geremy condra</a> (<a href="/recipes/tags/annotations/">annotations</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/function/">function</a>). Revision 3. </p> <p>This small snippet came about as a result of this discussion on python-ideas, requesting a new syntax for dynamically reevaluating a function each time it is called.</p> <p>It is a minor alteration of version 2 of this recipe that, instead of calling eval() on string annotations, simply requires that the annotations be callable and calls them at runtime.</p> Reevaluate functions when called, v2 (Python) 2009-05-14T15:10:51-07:00geremy condrahttp://code.activestate.com/recipes/users/4170000/http://code.activestate.com/recipes/576753-reevaluate-functions-when-called-v2/ <p style="color: grey"> Python recipe 576753 by <a href="/recipes/users/4170000/">geremy condra</a> (<a href="/recipes/tags/annotations/">annotations</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/function/">function</a>). </p> <p>As with version 1 of this recipe, it was sparked by a discussion on python-ideas about adding a special syntax to function signatures for reevaluating the arguments to a function at runtime. The below is a decorator and annotation based solution to this problem which stores the code to be evaluated as a string in the annotations, rather than reevaluating the entire function every time it is called.</p>