decorators tutorials

Diez B. Roggisch deets at nospam.web.de
Mon Jul 23 11:24:34 EDT 2007


james_027 wrote:

> hi bruno,
> 
> That seems to be hard to read at all, or I am just very new to python?
> 
> 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')

A decorator can alter the function _in place_ - it is not neccessary to
alter code that calls my_func, as your example does. 

As an additional benefit, it separates concerns - my_func does some stuff,
but mixing it with login-related logic is cumbersome:

def my_func(parameters):
    if not logged_in():
       do some redirection
    do_the_real_work()

is much more error-prone than

@check_login
def my_func(parameters):
   do_the_real_work()

because then you can just skim the decorator and concentrate on the actual
code.

What one often reaches with decorators is something referred to as "aspect
orientied programming". 

Diez



More information about the Python-list mailing list