Chaining decorators result is confusing me

Question:

def decor1(func):
    def inner():
        x = func()
        return x * x
    return inner
 
def decor(func):
    def inner():
        x = func()
        return 2 * x
    return inner
 
@decor1
@decor
def num():
    return 10
 
print(num())

Can someone explain why the result is 400?
Is it because inner is being returned twice?
I’m learning chaining decorators but it’s a bit confusing at first glance.

Asked By: brian.p

||

Answers:

The num function returns 10, which is then passed to decor (one level higher) in variable x (note that func() refers to num(), hence it returns 10). x is multiplied by 2, yielding 20. The 20 is passed to decor1 (another level higher) in variable x and is multiplied by itself, so 20 times 20 yields 400.

Answered By: DSteman

The first decorator applied is @decor, so at this stage your num function will return 2*10.
Then @decor1 is applied so in the end num returns (2*10)*(2*10) which is 400.

Answered By: YuriC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.