Estimated reading time: 2 minutes
This is a common TypeError that you will come across in Python, it is actually easy to diagnose how it occurred.
To start off we need to understand “str” is a function in python, and it converts any value into a string.
As a result , because it is a function your ability to call it has limitations.
So in essence it has parenthesis () beside it, and allows parameters to be passed to it.
So lets first look at how the string function works:
x = str("10") y = 10 print(type(x)) print(type(y)) print(x) print(y) With output: <class 'str'> <class 'int'> 10 10
As you will see the above the value 10, on its own is an integer, but when you call the string function, it now becomes a string.
For this reason this , calling a string function , completes a conversion to string of ten, but what if the variable is called str?
Lets take an example below from an input:
str = input("what year where you born?") print(str(str)) Output: what year where you born?2021 Traceback (most recent call last): File "str obj is not callable.py", line 2, in <module> print(str(str)) TypeError: 'str' object is not callable Process finished with exit code 1
The reason for this error above , is that we have named the variable “str”.
As can be seen the programme is trying to use the first str in the print statement as a function.
As we know by now string variables are not callable.
Accordingly the function str() which the programme is trying to run, fails with the TypeError identified.
For this reason to fix this problem we would change the variable called str to “year”, the error then disappears.
The updated code will work as when calling str(), it is not conflicted with a variable name.
year = input("what year where you born?") print(str(year)) Output: "str obj is not callable.py" what year where you born?2021 2021 Process finished with exit code 0
So to summarise:
- Strings are not callable
- Don’t name a variable as str, or any function name, these are reserved words by the system.
- Functions are callable, strings are not.