+ 3

What is the use of nested function inside decorator function while we are getting same result without it?

20th Jul 2020, 10:12 AM
Sarfira
Sarfira - avatar
5 ответов
+ 2
Théophile def decor(func): print("============") func() print("============") def print_text(): print("Hello world!") print_text = decor(print_text) this code gives the same result even without wrap then why do we use wrap and print text at the end
20th Jul 2020, 10:18 AM
Sarfira
Sarfira - avatar
+ 2
A decorator must return a function. Look at your two codes. In the fisrt one, the "decorator" returns None. So : print_text = decor(print_text) # print_text is now None, and cannot be called again. In your second example, the decorator returns a function, so print_text is still a function and can be used again. I think you misunderstood the purpose of decorators. The goal of a decorator is to "modify" the behavior of a function, and that's all! In your first example, you don't change the behavior of print_text.
20th Jul 2020, 10:27 AM
Théophile
Théophile - avatar
+ 1
def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decorated = decor(print_text) decorated() This is the original one where without using wrap function we are getting the same result..
20th Jul 2020, 10:22 AM
Sarfira
Sarfira - avatar
+ 1
Théophile then func() is also a function which is parameter of decor function what is use of that func function here & Can you please elaborate it?
20th Jul 2020, 10:35 AM
Sarfira
Sarfira - avatar
0
Can you provide an exemple? I don't see why you're saying that it is the same with a nested function and without a nested function...
20th Jul 2020, 10:16 AM
Théophile
Théophile - avatar