Python Decorators - Python Wiki
Python Wiki Python Wiki / Python Wiki / Archive / Python Decorators View as Markdown Python Decorators ¶ Legacy Wiki Page This page was migrated from the old MoinMoin-based wiki. Information may be outdated or no longer applicable. For current documentation, see python.org . About this page ¶ This page largely documents the history of the process of adding decorators to Python. If you’re just interested in what decorators or the ‘@’ symbol mean in Python, see the Wikipedia page http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators or PEP 318 .
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: http://en.wikipedia.org/wiki/Decorator_pattern 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 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 winning syntax as of now uses the ‘@’ symbol, as described in this message . Mark Russell implemented this version. Here is the message describing the patch he checked in. There has been a long discussion about the syntax to use for decorators in Python.
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. Current Python Decorator Proposals ¶ See section 6 for a categorization of different proposals; this section just provides concrete examples. Decorator Poll (consider the poll now closed) Here is an online poll where you can vote between a few different alternative syntaxes for python decorators: http://wiki.wxpython.org/index.cgi/PythonDecoratorsPoll A more complete poll is currently running on comp.lang.python, with the unfortunate name of “Alternate decorator syntax decision”, using the options on this WikiPage as the candidates.
Please visit that thread and express your preference! After the @decorator syntax was “accepted”, lots of people threw up alarms and a huge series of threads started exploding on Python-dev. Here are the current alternatives that I could find that are being argued, with pros and cons. I give two examples that might be common uses in the future. Classmethod declarations, and something like static typing (adapters), declaring what type parameters a function expects and returns.
A1. pie decorator syntax ¶ @classmethod def foo(arg1,arg2): ... @accepts(int,int) @returns(float) def bar(low,high): ... + Implementation already exists (and is in Python 2.4a2) + Java-like, so not completely unknown to everyone. + Makes the syntax obvious visually (i.e., obviously not a normal statement) + Will not be silently ignored + Compile-time + One decorator per line (makes it clearer to read, write and change order of decorators) + Separate from the def syntax (desired by some for making decoration stand out and keeping def the same) + Currently not used in Python so @decorators can be inserted anywhere, such as after parameters or inside expressions. + All decorators line up in one column immediately above the function name (easy to browse and see what’s going on). + The @ special character will make syntax highlighting easier than it would be for normal statements in “magic” locations. - Separate from the def syntax (undesired by some for simple decorators like classmethod/staticmethod) - Ugly? - Introduces a new character in the language - The @ special character is used in IPython and Leo - Punctuation-based syntax raises Perlfears.
But no “obvious” keyword or expression has been suggested. - @ is a relatively arbitrary character choice; no intuitive reason why it would indicate a decorator 0 The @ character is often used (in other languages) to mean “attribute”. For annotations, this is good. For more active decorators, it may not be so good. - Some people would like the @ character to be available as an overloadable operator - for example, as a binary operator for matrix multiplication (element-by-element and matrix multiplication may be usefully applied to a single object, so there’s arguably a need for a new operator rather than simply overriding binary * on a Matrix class). - Because of no indentation, looks confusing when definitions are not separated by empty lines.
But adding empty lines makes it hard to determine where the function definition truly starts. - That’s the first case in Python where a line following another one with the same identation has a meaning. - Breaks in interactive shell - Comes before the def keyword. Supercedes the function declaration itself, thus applying modifications implicitly to something not yet defined. - @staticmethod may look like staticmethod is not a defined variable, but a compile time option - Requires the programmer to scan an arbitrary distance from the def in *both* directions to see everything of interest (arg, decs, etc.). - Cannot be “folded” by editors as easily, as an arbitrary number of prefix lines should be folded with the body (otherwise, folding becomes less useful). - While the Language Spec does not promise that this character won’t be used, neither does it reserve *any* character for user extensions. ‘@’ is one of only three that are available, and another ‘$’ is also likely to get used up by 2.4 FWIW, here is Guido’s jumble example in this syntax. class C(object): @staticmethod @funcattrs(grammar="'@' dotted_name [ '(' [arglist] ')' ]", status="experimental", author="BDFL") def longMethodNameForEffect(longArgumentOne=None, longArgumentTwo=42): """This method blah, blah.
It supports the following arguments: - longArgumentOne -- a string giving ... - longArgumentTwo -- a number giving ... blah, blah. """ raise NotYetImplemented And here is an example taken from the current test_decorators.py. This exposes the problem of using two lines together with some meaning but without identation or vertical whitespace. class TestDecorators(unittest.TestCase): ... def test_dotted(self): decorators = MiscDecorators() @decorators.author('Cleese') def foo(): return 42 self.assertEqual(foo(), 42) self.assertEqual(foo.author, 'Cleese') A2. pie decorator and space syntax ¶ @ classmethod def foo(arg1,arg2): ... @ accepts(int,int) @ returns(float) def bar(low,high): ... * 0 This is more readable for some people, less readable for others.
B. list-before-def syntax ¶ [classmethod] def foo(arg1,arg2): ... [accepts(int,int), returns(float)] def bar(low,high): ... + Implementation already exists + C# like + Can be made backwards compatible-ish, with a “hack” + Doesn’t cause breakage in existing code-searching tools + Use visually existing syntax - Doesn’t cause breakage in existing code-searching tools - Would not work in interactive mode (list would be interpreted right away) - EuroPython didn’t like it ( why? ) (hard to teach newbies about the magic) - The backwards compatability wouldn’t be portable to Jython - Looks like a normal expression, but has “magic” behavior of altering a function object - Breaks in interactive shell - Har
The rest of this page is on the live site.