decorators ?

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Nov 30 14:38:46 EST 2004


"km" <km at mrna.tn.nic.in> wrote in message
news:mailman.6942.1101835501.5135.python-list at python.org...
> Hi all,
>  was going thru the new features introduced into python2.4 version.
> i was stuck with 'decorators' -  can someone explain me the need of such a
thing called decorators ?
> tia
> KM

Here are some example on the Python Wiki:
http://www.python.org/moin/PythonDecoratorLibrary

I think memoize is my favorite so far.

I'm not sure if the example behavior is all that clear.  For a given set of
arguments, the Memoize class keeps a dictionary of input arg values and
return values.  In subsequent calls, sets of args are looked up in the
dictionary of previous calls - if the arg list is found, then the function
is bypassed, and the cached return value is returned immediately.  This can
greatly speed up calls to functions that are very time-consuming, or
recursive.  This is why the Wiki page lists factorial() and fibonacci()
examples.  Of course, Memoize assumes that the return value is purely a
function of the input args, and not subject to any external state.

Of course, one could readily implement this behavior within the target
functions.  The beauty of the decorator is that this optimization is done
*completely* outside the function itself, so the function remains fairly
pure at the application level, and does not get cluttered with variables
like "resultsCache" and so on.  Also, in the interests of maximizing reuse
and avoiding the bug-proneness of cut-and-paste, isolating Memoize into a
reusable decorator helps avoid introducing bugs (vs. hard-coding this
optimization into successive functions - did you remember to initialize the
dictionary?), and leverages any optimizations or bug-fixes.

(I focused on Memoize, but these comments apply to any of the decorators on
this wiki page.)

-- Paul





More information about the Python-list mailing list