This content originally appeared on DEV Community 👩💻👨💻 and was authored by Reza Lavarian
✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
The “TypeError: ‘str’ object is not callable” error occurs when you try to call a string value (str
object) as if it was a function!
Here’s what the error looks like:
Traceback (most recent call last):
File "/dwd/sandbox/test.py", line 5, in
print(str + str(age))
^^^^^^^^
TypeError: 'str' object is not callable
Calling a string value as if it's a callable isn't what you'd do on purpose, though. It usually happens due to a wrong syntax or overriding a function name with a string value.
Let's explore the common causes and their solutions.
How to fix TypeError: 'str' object is not callable?
This TypeError happens under various scenarios:
- Declaring a variable with a name that's also the name of a function
- Calling a method that's also the name of a property
- Calling a method decorated with
@property
Declaring a variable with a name that's also the name of a function: A Python function is an object like any other built-in object, such as str
, int
, float
, dict
, list
, etc.
All built-in functions are defined in the builtins
module and assigned a global name for easier access. For instance, str()
refers to the __builtins__.str()
function.
That said, overriding a function (accidentally or on purpose) with a string value is technically possible.
In the following example, we have two variables named str
and age
. To concatenate them, we need to convert age
to a string value by using the built-in str()
function.
str = 'I am ' # ⚠️ str is no longer pointing to a function
age = 25
# ⛔ Raises TypeError: 'str' object is not callable
print(str + str(age))
If you run the above code, Python will complain with a "TypeError: 'str' object is not callable" error because we've assigned str
to another value ('I am '
). and 'I am '
isn't callable.
You have two ways to fix the issue:
- Rename the variable
str
- Explicitly access the
str()
function from the builtins module (__bultins__.str
)
The second approach isn't recommended unless you're developing a module. For instance, if you want to implement an open()
function that wraps the built-in open()
:
# Custom open() function using the built-in open() internally
def open(filename):
# ...
__builtins__.open(filename, 'w', opener=opener)
# ...
In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you've done so, renaming the variable would solve the issue.
So the above example could be fixed like this:
text = 'I am '
age = 25
print(text + str(age))
# Output: I am 25
This issue is common with function names you're more likely to use as variable names. Functions such as str
, type
, list
, dir
, or even user-defined functions.
In the following example, we declare a variable named len
. And at some point, when we call len()
to check the input, we'll get an error:
len = '' # ⚠️ len is set to an empty string
name = input('Input your name: ')
# ⛔ Raises TypeError: 'str' object is not callable
if (len(name)):
print(f'Welcome, {name}')
To fix the issue, all we need is to choose a different name for our variable:
length = ''
name = input('Input your name: ')
if (len(name)):
print(f'Welcome, {name}')
⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!
Overriding functions (and calling them later on) is the most common cause of the "TypeError: 'str' object is not callable" error. It's similar to calling integer numbers as if they're callables.
Now, let's get to the less common mistakes that lead to this error.
Calling a method that's also the name of a property: When you define a property in a class constructor, any further declarations of the same name (e.g., methods) will be ignored.
class Book:
def __init__(self, title):
self.title = title
def title(self):
return self.title
book = Book('Head First Python')
# ⛔ Raises "TypeError: 'str' object is not callable"
print(book.title())
In the above example, since we have a property named title
, the method title()
is ignored. As a result, any reference to title
will return the property title
, which returns a string value. And if you call this string value like a function, you'll get the "TypeError: ‘str’ object is not callable" error.
The name get_title
sounds like a safer and more readable alternative:
class Book:
def __init__(self, title):
self.title = title
def get_title(self):
return self.title
book = Book('Head First Python')
print(book.get_title())
# Output: Head First Python
Calling a method decorated with @property
decorator: The @property
decorator turns a method into a “getter” for a read-only attribute of the same name.
class Book:
def __init__(self, title):
self._title = title
@property
def title(self):
"""Get the book price"""
return self._title
book = Book('Head First Python')
# ⛔ Raises "TypeError: 'str' object is not callable"
print(book.title())
You need to access the getter method without the parentheses:
class Book:
def __init__(self, title):
self._title = title
@property
def title(self):
"""Get the book price"""
return self._title
book = Book('Head First Python')
print(book.title)
# Output: Head First Python
Problem solved!
Alright, I think it does it! I hope this quick guide helped you fix your problem.
Thanks for reading.
❤️ You might like:
- How to fix "‘float’ object is not callable" in Python
- How to fix "'int' object is not callable" in Python
- How to fix "Not all arguments converted during string formatting error" in Python
This content originally appeared on DEV Community 👩💻👨💻 and was authored by Reza Lavarian
Reza Lavarian | Sciencx (2023-02-03T13:49:29+00:00) How to fix “‘str’ object is not callable” in Python. Retrieved from https://www.scien.cx/2023/02/03/how-to-fix-str-object-is-not-callable-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.