Live data from Hacker News

Understanding Python Decorators

stackoverflow.com

1–10 of 28 posts

Re: Understanding Python Decorators

#5
post #2

I must say that for such a simple concept as decorator, this answer surely used up all the wireframe there ever was allocated for making examples.

I am pretty sure the Python community is always up for better explanations!

Better explanations?

   @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.

Re: Understanding Python Decorators

#7
post #5

Earlier quoted context omitted.

I am pretty sure the Python community is always up for better explanations!

Better explanations? @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.

>That is all there is to it.

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.

Re: Understanding Python Decorators

#8
post #5

Earlier quoted context omitted.

I am pretty sure the Python community is always up for better explanations!

Better explanations? @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.

Well, OK, but the answer also addresses other cases such as function/method decoration, passing arguments to the decorator itself, and passing arbitrary arguments. I agree that it's a little verbose, and the excessive comments and examples do detract from the clarity of the answer a little, but it's an excellent answer, nevertheless, if only because it leaves no use cases unexplored (excepting class decoration, but that's sufficiently orthogonal, I feel).

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.

Post reply on HN