Revision 134 as of 2004-10-21 18:34:08

Clear message

TableOfContents()

What is a Decorator

A decorator is the name used for a software design pattern. Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated.

For more information about the decorator pattern in general, see:

What is a Python Decorator

The "decorators" we talk about with concern to Python are not exactly the same thing as the DecoratorPattern described above. A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well.

Support for the decorator syntax was proposed for Python in [http://www.python.org/peps/pep-0318.html PEP 318], and will be implemented in Python 2.4.

Note that the current proposal actually only decorates functions (including methods). Extending it to classes or even arbitrary code is possible, but Guido wasn't sure it made sense. (Later versions might become more permissive, but they can't easily snatch functionality back.)

Debate about decorators in Python

The syntax for decorators uses the '@' symbol, as described in [http://mail.python.org/pipermail/python-dev/2004-June/045516.html this message]. Mark Russell implemented this version. [http://mail.python.org/pipermail/patches/2004-July/015452.html Here] is the message describing the patch he checked in.

There was a long discussion about the syntax to use for decorators in Python. May different proposals were suggested: see PythonDecoratorProposals.

Examples

   1 @classmethod
   2 def foo (arg1, arg2):
   3     ....

See PythonDecoratorLibrary for more complex and real-world examples. See also MixIns and MetaClasses for related resources.

Unable to edit the page? See the FrontPage for instructions.