brian.p
brian.p

Reputation: 77

Chaining decorators result is confusing me

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.

Upvotes: 1

Views: 144

Answers (2)

ychiucco
ychiucco

Reputation: 800

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.

Upvotes: 2

DSteman
DSteman

Reputation: 1658

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.

Upvotes: 2

Related Questions