0

can some one tell me which fuction is being called first and which one is called at last here inner() function return fun(a,b) but instead of execution it is passing parameter to function iny() . how that's possible?

def deco(fun):
 def inner(a,b):
 if a<b:
 a,b=b,a
 print(a,b)
 return fun(a,b)
 return inner
def smart(fun):
 def iny(a,b):
 a,b=a+1,b+1
 print(a,b)
 return fun(a,b)
 return iny
'''@deco
@smart'''
def div(a,b):
 return a/b
di=deco(smart(div))(4,8)
print(di)
Avinash Raj
175k32 gold badges246 silver badges289 bronze badges
asked Jul 19, 2019 at 6:03

1 Answer 1

1

Your code is essentially the same as:

def div(a, b):
 return a/b
def smart(a, b):
 a,b=a+1,b+1
 print(a,b)
 return div(a,b)
def deco(a, b):
 if a<b:
 a,b=b,a
 print(a,b)
 return smart(a,b)
di=deco(4,8)
print(di)

In your code fun from inner is set to iny from smart and fun from iny is set to div.

To explain the order I give you a simplified example with functions named outer and inner for their respective positions:

def outer(inner_fun):
 def outer_inner(a, b):
 print("outer")
 inner_fun(a, b)
 return outer_inner
@outer
def inner(a, b):
 print("inner")
 print(a, b)
inner(1, 2)

This outputs:

outer
inner
1 2

When we call inner(1, 2) first inner is given to outer. outer returns a function outer_inner where inner_fun is now set to inner. If there were another decorator (like in your example) the next decorator would be called with outer_inner as argument. But because there is no further decorator, outer_inner is being called with the arguments (1, 2) which prints "outer" and calls the function inner (because inner_fun is set to inner). Then the function inner prints "inner" and the two numbers.

So in general: the outermost decorator is called first and then the inner decorators are called in their respective order.

answered Jul 19, 2019 at 6:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.