decorators tutorials
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Jul 23 11:46:03 EDT 2007
james_027 a écrit :
> hi bruno,
>
> That seems to be hard to read at all, or I am just very new to python?
or just new to higher order functions ? (ie: functions working on
functions).
> With that decorator how do I take advantage of it compare when I just
> write a function that could do the same as what the decorator did? I
> could translate the could from above into ...
>
> def check_login(msg):
> #...
> def my_func(toto, tata):
> #...
>
> #call it like this
> check_login('msg')
> my_func('toto', 'tata')
The first (and already very important difference) is that, with your
solution, you have to remember to explicitely call check_login before
calling my_func, while the decorator will take care of this. This allow
to factor out orthogonal behaviours (like permission management, logging
etc). Now there are almost endless other possible uses - anything that
requires adding metadata to functions (CherryPy's way of flagging
request handlers), registering functions for later use (ie: entry points
for a plugin system, rule-based dispatch etc), triggering other
behaviours before and/or after the function call - possibly bypassing
the call to the original function, etc, etc, etc.
Note that the important part here is not the @decorator syntax - which
is just (nice) syntactic sugar - but the ability to use higher order
functions.
More information about the Python-list
mailing list