python - Why we use wrapper in decorator , when we can create decorator without wrapper? -
i reading python decorators , found them useful , have confusion tried search on google , stackoverflow couldn't found answer , 1 questions asked on stackoverflow same title question talk @wrap , question different :
so basic decorator template :
def deco(x): def wrapper(xx): print("before deco") x(xx) print("after deco") return wrapper def new_func(a): print("this new function") wow=deco(new_func) print(wow(12))
which result :
before deco new function after deco none
so whenever deco return call wrapper function , not getting why using wrapper when our main goal passing new_func parameter deco function , calling parameter in deco function , if try can create same thing without wrapper function here :
def deco(x): print("before deco") a=1 x(a) print("after deco") def new_func(r): print("this new function") wow=deco(new_func) print(wow)
which result :
before deco new function after deco none
so use of wrapper in decorator ?
here's question may help. let's change new_func
uses parameter it's passed. e.g.
def new_func(r): print("new_func r:", r)
suppose have another_func
passes parameter new_func
:
def another_func(): new_func(999)
the question is, how write deco
that
another_func
continues work without change andnew_func
recieves whatever value passedanother_func
?
Comments
Post a Comment