+ 1

Python Decortors - Small question

we have the code ..................................................... def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decorated = decor(print_text) decorated() .............................................................. that's cool and I understand that completely, but why did i put another function (wrap) i think it's just a waste of time, couldn't I type this code... ........................................................... def decor(func): print("============") func() print("============") def print_text(): print("Hello world!") decor(print_text) .................................................................. basically, i called the function 'print_text' inside the function 'decor', isn't that easier??

17th Jan 2023, 8:48 AM
Karim Maasarani
Karim Maasarani - avatar
5 Respostas
17th Jan 2023, 10:46 AM
Lothar
Lothar - avatar
+ 4
Notice how you are calling function in both versions. In first version, you are calling the function by: -> decorated() in the second:- -> decor(print_text) Try to modify the second function call to look like first: -> decorated = decor(print_text) -> decorated() _____________________________________ Above leads to error because, in the second version you are not returning callable from "decor()". (see sololearners explanation) If we don't use "wrap" inner function, we have to modify "decorated()" to "decor(print_text)" and this might not be easy if the function we are modifying is used many times in our project and could lead to errors. Using an inner function saves us from all this extra work.
17th Jan 2023, 7:05 PM
Sandeep
Sandeep - avatar
+ 3
your second example is not a decorator. It's just a function calling another function. Notice you are using the decorator function name. In a decorator pattern, you use the inner function name. The decorator modifies the result. Also, passing arguments in your second example becomes tricky.
17th Jan 2023, 11:54 AM
Bob_Li
Bob_Li - avatar
+ 3
#you need a wrapper function inside. #try to make the same generic decorator without the inner wrap function. #generic decorator def allcaps(foo): def wrap(*a,**kw): return foo(*a,**kw).upper() return wrap #normal functions def hello(n): return f"hello {n}" def goodbye(n): return f"bye {n}" #normal results print(hello('peter')) print(goodbye('megan')) #decorated functions @allcaps def hello(n): return f"hello {n}" @allcaps def goodbye(n): return f"bye {n}" #decorated results print(hello('peter')) print(goodbye('megan'))
17th Jan 2023, 12:13 PM
Bob_Li
Bob_Li - avatar
+ 3
Thank you @Lothar @sandeep @Mirielle @Bob_Li
22nd Jan 2023, 3:37 PM
Karim Maasarani
Karim Maasarani - avatar