Can anyone explain why this code returns TypeError? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can anyone explain why this code returns TypeError?

def decor(func): return "=" + func()+ "=" @decor def sayhi(): return "sayhi" print(sayhi())

30th Apr 2021, 9:04 AM
Gbadegesin Muhammed
Gbadegesin Muhammed - avatar
6 Answers
+ 7
As it is with y in the decor function, it will give you a NameError since the variable name y doesn't exist in that scope. I'm going to assume you meant for y to be func() so that it would look like; def decor(func): return "=" + func() + "=" In which case you will get a TypeError, because 'sayhi' is of type 'str' string and is not callable. To then get the expected output of; "=sayhi=" you would need to remove the parentheses from your attempt to call the function in the print call print(sayhi) # change this to fix code In case your wondering why, it's because your decorator is functioning the same as this; def decor(func): return "=" + func() + "=" def sayhi(): return "sayhi" decor_func = decor(sayhi) # decor_func is a string print(decor_func)
30th Apr 2021, 9:31 AM
ChaoticDawg
ChaoticDawg - avatar
+ 5
y is not a string, but "y" is. plus, the error will tell you what line and also give you more info like what type can't be added to what
30th Apr 2021, 9:12 AM
Slick
Slick - avatar
+ 3
You did not yet fully understand decorator. decor should return a function.
30th Apr 2021, 9:28 AM
Oma Falk
Oma Falk - avatar
+ 1
Slick ,Frogged ,ChaoticDawg There was a typo error in code and it has been corrected now, pls can you still help check why it is returning TypeError. Thank you guys
30th Apr 2021, 9:42 AM
Gbadegesin Muhammed
Gbadegesin Muhammed - avatar
+ 1
Gmuhammed🇳🇬 (CHALLENGE ACCEPTED) I already answered and explained, as I assumed there was this typo.
30th Apr 2021, 9:46 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
ChaoticDawg Thank you, I understand now.
30th Apr 2021, 9:59 AM
Gbadegesin Muhammed
Gbadegesin Muhammed - avatar