Please explain why i am getting a type error along with the expected output in the below decorator program. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Please explain why i am getting a type error along with the expected output in the below decorator program.

My code: def decor(func): print("============") func() print("============") @decor def print_text(): print("Hello world!") print_text(); Output: ============ Hello world! ============ Traceback (most recent call last): File "..\Playground\", line 11, in <module> print_text(); TypeError: 'NoneType' object is not callable

7th Aug 2017, 9:49 AM
Rahul V.Kumar
4 Answers
+ 12
Your decorator needs to return a function, but it's not returning anything, hence the 'TypeError: 'NoneType' object is not callable'.  Try doing: def decor(func): def decorated(): print("============") func() print("============") return decorated @decor def print_text(): print("Hello world!")
7th Aug 2017, 10:06 AM
Hatsy Rei
Hatsy Rei - avatar
+ 9
When we are doing @decor def print_text(): print("Hello world!") What happens underneath the hood is def print_text(); print("Hello world!") print_text = decor(print_text) This is why decor must return the internal function wrapper (in the case, decorated). Take a closer look at the third line print_text = decor(print_text) decor() takes print_text as a parameter, and returns the internal wrapper, which consist of the bars along with text. Where does it return to? It is returned back to print_text. So now, print_text actually stores the definition of decor's internal wrapper with the initial print_text definition.
7th Aug 2017, 11:25 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
@Hatsy Rei Thank you for the solution. I was trying to avoid the usage of extract function decorated(). It will work if we are calling the function like decor(print_text); def decor(func): print("============") func() print("============") def print_text(): print("Hello world!") decor(print_text); But while using "@" we need to have a decorative function which should RETURN SOMETHING. So we need to use a nested function like decorated() inside decor(). def decor(func): def decorated(): print("============") func() print("============") return decorated @decor def print_text(): print("Hello world!") Please let me know whether my understanding is correct or not. Once again , thanks a lot for your quick response.
7th Aug 2017, 10:36 AM
Rahul V.Kumar
+ 1
Got it. Thanks Hatsy.
7th Aug 2017, 11:29 AM
Rahul V.Kumar