+ 1

Why do I have to write a inner function inside the decorator function?

I mean what is the reason i can't write only a common one an its performance like this: def decorer(func) : print("#######") func() print("#######") @decorer def func() : print ("****")

18th Aug 2021, 8:34 PM
Pol Escu
Pol Escu - avatar
2 odpowiedzi
+ 1
You have to create a nested function (you can call it: wrap() ) inside the decorator() and than the decorator function will return that nested function. The reason WHY is because you can only return something once (like this: return 'Hello' ) and then it will break out of the function and code that are under the return, will not run. So we created another function which will store some code, and can be returned. But I don't exactly know if that is the answer to your question. def decorer(func) : def wrap(): print("#######") func() print("#######") return wrap @decorer def func() : print("****") func()
18th Aug 2021, 8:49 PM
Baspberry
- 1
The only reason i see is the need to pass arguments.
18th Aug 2021, 8:37 PM
Abhay
Abhay - avatar