Reputation: 1538
I don't know if "Nested python decorator?" is the right way to state this question, so let me know if it's not.
Anyway, I'm taking a class at udacity and have just encountered some code that involves python decorator and looks like voodoo magic, so now I want to ask a generalized question to see if I can figure that code out.
Suppose that I have the following code:
def A(f):
print 'blah'
return f
@A
def B(f):
return f
@B
def C():
pass
Now, I understand that from the above code, the decorator causes B to turn into:
B = A(B)
and that's what a decorator does. However, what is C like? From some small sample codes I have seen, somehow C is affected by A because A changes B and B changes C. But I have two problems understanding this:
C = A(B)(C)
or C = A(B(C))
?Personal guess
Actually, now that I have typed it out, I hypothesize that what happens is we first get:
B = A(B)
and then C = B(C)
. It means that overall, we get C = A(B)(C)
, and it would explain why 'blah' is only printed once.
But it's best that I make sure.
Upvotes: 4
Views: 2391
Reputation: 526583
Your personal guess is correct.
A decorator is "called" at definition-time, when the @
-line and its following function definition are evaluated.
@foo
def bar():
pass
is just syntactic sugar for...
def bar():
pass
bar = foo(bar)
Upvotes: 6