Gabriel Genellina wrote: > At Tuesday 22/8/2006 17:19, Wolfgang Draxinger wrote: >> I'm just reading the python language reference and came around >> the term "decorated functions", but I have no idea, for what >> they could be used. > > A decorator takes a function/method/callable, "decorates" (modifies) > it in a certain way, and returns it.
It's important to note here that decorators, using the @decorate syntax[1], *can only decorate methods and functions*. That is, they must be followed by either another @decorator or a "def" statement. Anything else will result in a SyntaxError. For example: >>> def test(callable): return callable ... >>> @test ... def foo(): pass ... >>> @test ... @test ... @test ... def foo(): pass ... >>> @test ... class bar: File "<stdin>", line 2 class bar: ^ SyntaxError: invalid syntax >>> @test ... file File "<stdin>", line 2 file ^ SyntaxError: invalid syntax >>> So you can't decorate classes (the original PEP proposed it, but it was dropped - see the discussion about this on python-dev[2]). You *can* decorate a class' __init__ method, but that's not quite the same as eg. implementing @singleton (mind you, we already have a bazillion ways to implement the singleton pattern, so I don't think we're poorer for this limitation <wink>) Richard [1] of course, you can "anything = decorate(anything)" [2] http://mail.python.org/pipermail/python-dev/2005-March/052369.html -- http://mail.python.org/mailman/listinfo/python-list