What are decorators?

Peter Hansen peter at engcorp.com
Mon Aug 9 14:13:20 EDT 2004


gohaku wrote:

> The discussion on Python Decorators and "@" has piqued my interest on this
> "feature?" in programming languages such as Python and Java.
> can anybody what is the point in using Decorators?

In Python, at least, they seem to be syntactic sugar for the following,
as the PEP clearly shows:

def func():
     pass

func = decorator(func)


That is equivalent to this with the new proposed syntax (and this is
no doubt out of date because I wrote it more than two minutes ago):

@decorator
def func():
     pass


In other words, they are simply a function that takes a function
and does something to or with it, returning a new function, or
perhaps the old one, when it's done.

The original use cases seem to have been staticmethod and classmethod.
Python doesn't have special syntax for defining these, as for
example Java does, so the idiom shown first above was developed,
along with a staticmethod() or classmethod() "decorator" function
which would modify the original non-static method so that it was
now a static method.

The folks using this decided they didn't like the fact that the
modification came *after* the function definition, since it could
be hard to notice it, and probably they didn't really like the
feel of the whole thing, since it's sort of hackish and inelegant.

If you don't need staticmethod (and the answer to the question
"do I need staticmethod?" is "no"), then you don't really need
decorators. :-)

-Peter



More information about the Python-list mailing list