Understanding Python Decorators
stackoverflow.com
stackoverflow.com
Also, I wish they would integrate some of the stuff from this answer into the documentation, as it took me almost an hour to figure out how decorators that take arguments work and to discover that @decorator and @decorator() are irrevocably different. The documentation I found on decorators that take args was very brief. (I can't remember if I found any mention at all in the actual Python docs. I ended up learning it from mediocre, old blog posts)
def decorator():
return some_library.decorator_with_no_args
@decorator()> Decorators are somewhat of a pain because there is a difference between @foo and @foo(). If they were declared in a way that the former means the latter we would all be much happier now. Every time I want to introduce a parameter to a previously parameterless decorator makes me want to hit myself and the author of the decorator PEP with a stick.
http://lucumr.pocoo.org/2011/7/9/python-and-pola/
Discussed on HN too:
you can see what i mean here - http://code.google.com/p/lepl/source/browse/src/lepl/matcher...
this doesn't fix the problem completely, of course, but it does mean that a user that types @foo instead of @foo() gets a helpful warning explaining exactly what they have done wrong.
@a[1]
def f(x):
...I had a permission checking decorator that I allowed both syntaxes (the default permission check and a mre fine-grained check). The flaw makes for an ugly implementation.
Step 2: I bet I could ...
Step 3: Quick check of CPAN
Step 4: Zounds. http://search.cpan.org/~erwan/Python-Decorator-0.03/lib/Pyth...
Not to mention, one could alter the implementation to remove the inconsistency people are complaining about in Python.
@foo
def bar():
...
Is syntax sugar for def bar():
...
bar = foo(bar)
That is all there is to it. It's just syntax sugar to make this particular design pattern more convenient to use.These explanations add more confusion then they dissolve and give off the impression that this is some kind of expert python foo which is clearly isn't.
At it's most basic yes, but passing arguments to both the decorator and the decorated function are the real value of the article.
And there are examples, more than I need but they provide different ways of looking at the same thing that different people might find useful.
Your answer isn't wrong, but as an exercise in pedagogy (which is the point of SO, or at least one of its major aims) it leaves a lot to be desired, and wouldn't garner many upvotes. Not everyone understands what the term "syntax sugar" (and really, shouldn't that be 'syntactic sugar'?) means.
http://docs.python.org/dev/library/functools.html#functools....