Python - TypeError 'str' object is not callable | SoloLearn: Learn to code for FREE!


Python - TypeError 'str' object is not callable

Apparently this error arises when we try to call a string as a function. def decor(func): x= "=" return x + func() + x @decor def text(): return "zzz" print(text()) From my understanding @decor means text = decor(text). Does this mean that print(text()) is passing ' return "zzz" ' to the decor function? Is this where the type error arise?

9/20/2020 8:19:48 PM


12 Answers

New Answer


Decorators should return a function that wraps around the passed function, in your case, instead of returning a function you're returning a string surrounded by equal signs and since you can't call a string it raise an error, you can print it to check the value: print(text) # outputs =zzz= Or you can return a wrapper function, check this out:


Namit Jain but then why do we use decorator? decor(text) would do it too.


Oma Falk yaa 😌😅 Just telling him that what's the reason of the error 🙂 Actually, many a times I find decorators pointless (sorry, that's my opinion)


Bagon Namit Jain so just to clarify for me @decor func() changes the function func to a variable that holds decor(func)?


Try this! def decor(func): x= "=" return x + func() + x @decor def text(): return "zzz" print(text) # The brackets have been removed Output: =zzz= This happens because, As you interpreted correctly test becomes same as decor(text) So just printing text means you are calling the function decor that takes input as the actual text function! And now text = "=zzz=" You cannot call a str 😃


Bagon I guess there is no need of returning function 😃 See my answer ☺️ Returning function is done so that you can use the text() but the same thing can be done without returning a function and by: print(text)


Bagon Yaa ✅👍


Oma Falk Yaa 😃 It turns to a function if we use a wrapper else by @Solus's method it turns to a string/int etc


Bagon thanks pre-evolved Shelgon! Will remember to use the wrapper function onward.


Namit Jain yeah I find them pretty useless as well, almost everytime it's easier and better to just modify the function or add a helper one. Timing performance is the best use of decorators I've seen so far


Namit Jain yeah, noticed that too but in general, decorators purpose is to modify other function without actually touching it, so most of the times decorator just returns a function which you can call wherever and whenever you want. Not necessary in this case but pretty important in general, so I had to mention it. 😅


Try to use variable and assign it to text() then this variable x = text() print(x)