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())
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)
+ 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
+ 3
You did not yet fully understand decorator.
decor should return a function.
+ 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
+ 1
Gmuhammed🇳🇬 (CHALLENGE ACCEPTED)
I already answered and explained, as I assumed there was this typo.
+ 1
ChaoticDawg Thank you, I understand now.