Kiet Tran
Kiet Tran

Reputation: 1538

Nested python decorator?

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:

  1. The exact nature of C. Is it C = A(B)(C) or C = A(B(C))?
  2. 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.

Upvotes: 4

Views: 2391

Answers (1)

Amber
Amber

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

Related Questions