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:
- The exact nature of C. Is it
C = A(B)(C)orC = A(B(C))? - If C is indeed affected by A, why is ‘blah’ only printed once when I run the above code?
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.
Your personal guess is correct.
A decorator is “called” at definition-time, when the
@-line and its following function definition are evaluated.is just syntactic sugar for…