Decorators

Terry Reedy tjreedy at udel.edu
Fri Mar 6 13:44:57 EST 2009


Johny wrote:
> Hi,
> Can anyone explain to me what are decorators for? What are advantages
> of using them?

There are two questions: why wrap or modify a function after it is 
modified? (others have answered this), and why the special syntax?

As to the second:

@deco
def f(): pass

is syntactic sugar for

def f(): pass
f = deco(f)

with two advantages.  The 'sugar' informs the reader immediately that 
the function will be wrapped or modified, which could be missed if the 
body is long, and eliminates two repetitions of the function name, which 
could be a long_info_rich_coded_name such as required in some projects.

A subtle effect of having the special syntax is that it has directed 
more attention to the idea of post-processing functions and now, in 3.0, 
classes.

Terry Jan Reedy




More information about the Python-list mailing list