Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "TypeError: 'tuple' object is not callable" occurs when we try to
call a tuple as if it were a function. To solve the error, make sure to use
square brackets when accessing a tuple at a specific index, e.g.
my_tuple[0]
.
Here is one example of how the error occurs.
my_tuple = ('a', 'b', 'c') # ⛔️ TypeError: 'tuple' object is not callable my_tuple(0) # 👈️ uses parenthesis instead of square brackets
The issue in the code sample is that we used parenthesis instead of square brackets when accessing the tuple at a specific index.
my_tuple = ('a', 'b', 'c') print(my_tuple[0]) # 👉️ 'a' print(my_tuple[1]) # 👉️ 'b' print(my_tuple[2]) # 👉️ 'c'
Another thing to look out for is that you're not overriding the built-in
tuple()
function.
# 👇️ overriding built-in tuple() function tuple = ('a', 'b', 'c') # ⛔️ TypeError: 'tuple' object is not callable result = tuple(['d', 'e', 'f'])
To solve the error in this situation, rename your variable and restart your script.
# ✅ no longer overriding built-in tuple() function my_tuple = ('a', 'b', 'c') result = tuple(['d', 'e', 'f'])
Make sure you don't have two tuples next to one another without separating them with a comma.
# ⛔️ TypeError: 'tuple' object is not callable my_list = [('a', 'b') ('c', 'd')]
We have a missing comma between the two tuples in the list, so Python thinks we are trying to call the first tuple.
To solve the error, place a comma between the tuples.
my_list = [('a', 'b'), ('c', 'd')]
Another common cause of the error is simply trying to call a tuple as a function.
my_tuple = ('a', 'b', 'c') # ⛔️ TypeError: 'tuple' object is not callable my_tuple()
Make sure you don't have a function and a variable with the same name.
def example(): return 'hello world' example = ('a', 'b', 'c') # ⛔️ TypeError: 'tuple' object is not callable print(example())
example
variable shadows the function with the same name, so when we try to call the function, we actually end up calling the variable.Renaming the variable or the function solves the error.
The error is also caused when we have a class method and a class property with the same name.
class Employee(): def __init__(self, tasks): # 👇️ this attribute hides the method self.tasks = tasks # 👇️ same name as class variable def tasks(self): return self.tasks emp = Employee(('dev', 'test')) # ⛔️ TypeError: 'tuple' object is not callable print(emp.tasks())
The Employee
class has a method and an attribute with the same name.
To solve the error, you have to rename the class method.
class Employee(): def __init__(self, tasks): self.tasks = tasks def get_tasks(self): return self.tasks emp = Employee(('dev', 'test')) print(emp.get_tasks()) # 👉️ ('dev', 'test')
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructor