In Python, a “Typeerror” occurs when you use different data types in an operation.
For example, if you attempt to divide an integer (number) by a string, it leads to a typeerror
because an integer data type is not the same as a string.
One of those type errors is the “int object is not callable” error.
The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int()
, sum()
, max()
, and others.
The error also occurs when you don’t specify an arithmetic operator while performing a mathematical operation.
In this article, I will show you how the error occurs and what you can do to fix it.
How to Fix Typeerror: int object is not callable
in Built-in Function Names
If you use a built-in function name as a variable and call it as a function, you’ll get the “int object is not callable” error.
For instance, the code below attempts to calculate the total ages of some kids with the built-in sum()
function of Python. The code resulted in an error because the same sum
has already been used as a variable name:
kid_ages = [2, 7, 5, 6, 3]
sum = 0
sum = sum(kid_ages)
print(sum)
Another example below shows how I tried to get the oldest within those kids with the max()
function, but I had declared a max
variable already:
kid_ages = [2, 7, 5, 6, 3]
max = 0
max = max(kid_ages)
print(max)
Both code examples led to this error in the terminal:
To fix the issue, you need to change the name of the variable you named as a built-in function so the code can run successfully:
kid_ages = [2, 7, 5, 6, 3]
sum_of_ages = 0
sum = sum(kid_ages)
print(sum)
# Output: 23
kid_ages = [2, 7, 5, 6, 3]
max_of_ages = 0
max = max(kid_ages)
print(max)
# Output: 7
If you get rid of the custom variables, your code will still run as expected:
kid_ages = [2, 7, 5, 6, 3]
sum = sum(kid_ages)
print(sum)
# Output: 23
kid_ages = [2, 7, 5, 6, 3]
max = max(kid_ages)
print(max)
# Output: 7
How to Fix Typeerror: int object is not callable
in Mathematical Calculations
In Mathematics, if you do something like 4(2+3), you’ll get the right answer which is 20. But in Python, this would lead to the Typeerror: int object is not callable
error.
To fix this error, you need to let Python know you want to multiply the number outside the parentheses with the sum of the numbers inside the parentheses.
To do this, you do this by specifying a multiplication sign (*) before the opening parenthesis:
print(4*(2+3))
#Output: 20
Python allows you to specify any arithmetic sign before the opening parenthesis.
So, you can perform other calculations there too:
print(4+(2+3))
# Output: 9
print(4-(2+3))
# Output: -1
print(4/(2+3))
# Output: 0.8
Final Thoughts
The Typeerror: int object is not callable
is a beginner error in Python you can avoid in a straightforward way.
As shown in this article, you can avoid the error by not using a built-in function name as a variable identifier and specifying arithmetic signs where necessary.
Thank you for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.
Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.
Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError
, которые не стоит пытаться обработать.
Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.
Ошибки могут быть разных видов:
- Синтаксические
- Недостаточно памяти
- Ошибки рекурсии
- Исключения
Разберем их по очереди.
Синтаксические ошибки (SyntaxError)
Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.
Рассмотрим на примере.
a = 8
b = 10
c = a b
File "", line 3
c = a b
^
SyntaxError: invalid syntax
Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.
Недостаточно памяти (OutofMemoryError)
Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap
). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory
. Она может появиться по нескольким причинам:
- Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
- Загрузка файла большого размера;
- Запуск модели машинного обучения/глубокого обучения и много другое;
Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError
, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.
Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()
), не факт, что все процессы восстановятся — в некоторых случаях MemoryError
приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.
Ошибка рекурсии (RecursionError)
Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.
Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.
Чтобы воспроизвести эту ошибку, определим функцию recursion
, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow
или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.
def recursion():
return recursion()
recursion()
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
in
----> 1 recursion()
in recursion()
1 def recursion():
----> 2 return recursion()
... last 1 frames repeated, from the frame below ...
in recursion()
1 def recursion():
----> 2 return recursion()
RecursionError: maximum recursion depth exceeded
Ошибка отступа (IndentationError)
Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.
Пример:
for i in range(10):
print('Привет Мир!')
File "", line 2
print('Привет Мир!')
^
IndentationError: expected an indented block
Исключения
Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.
Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:
Ошибка типа (TypeError)
a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
1 a = 2
2 b = 'PythonRu'
----> 3 a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Ошибка деления на ноль (ZeroDivisionError)
10 / 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
in
----> 1 10 / 0
ZeroDivisionError: division by zero
Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError
и ZeroDivisionError
. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.
Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.
Теперь рассмотрим встроенные исключения Python.
Встроенные исключения
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.
Try
: он запускает блок кода, в котором ожидается ошибка.Except
: здесь определяется тип исключения, который ожидается в блокеtry
(встроенный или созданный).Else
: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).Finally
: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.
В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.
Ошибка прерывания с клавиатуры (KeyboardInterrupt)
Исключение KeyboardInterrupt
вызывается при попытке остановить программу с помощью сочетания Ctrl + C
или Ctrl + Z
в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.
В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt
. Теперь обработаем исключение KeyboardInterrupt
.
try:
inp = input()
print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
print('Исключение KeyboardInterrupt')
else:
print('Исключений не произошло')
Исключение KeyboardInterrupt
Стандартные ошибки (StandardError)
Рассмотрим некоторые базовые ошибки в программировании.
Арифметические ошибки (ArithmeticError)
- Ошибка деления на ноль (Zero Division);
- Ошибка переполнения (OverFlow);
- Ошибка плавающей точки (Floating Point);
Все перечисленные выше исключения относятся к классу Arithmetic
и вызываются при ошибках в арифметических операциях.
Деление на ноль (ZeroDivisionError)
Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.
try:
a = 100 / 0
print(a)
except ZeroDivisionError:
print("Исключение ZeroDivisionError." )
else:
print("Успех, нет ошибок!")
Исключение ZeroDivisionError.
Переполнение (OverflowError)
Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.
try:
import math
print(math.exp(1000))
except OverflowError:
print("Исключение OverFlow.")
else:
print("Успех, нет ошибок!")
Исключение OverFlow.
Ошибка утверждения (AssertionError)
Когда инструкция утверждения не верна, вызывается ошибка утверждения.
Рассмотрим пример. Предположим, есть две переменные: a
и b
. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert
, что приведет к вызову исключения Assertion
в том случае, если выражение будет ложным.
try:
a = 100
b = "PythonRu"
assert a == b
except AssertionError:
print("Исключение AssertionError.")
else:
print("Успех, нет ошибок!")
Исключение AssertionError.
Ошибка атрибута (AttributeError)
При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes
нет атрибута с именем attribute
.
class Attributes(obj):
a = 2
print(a)
try:
obj = Attributes()
print(obj.attribute)
except AttributeError:
print("Исключение AttributeError.")
2
Исключение AttributeError.
Ошибка импорта (ModuleNotFoundError)
Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.
import nibabel
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
in
----> 1 import nibabel
ModuleNotFoundError: No module named 'nibabel'
Ошибка поиска (LookupError)
LockupError
выступает базовым классом для исключений, которые происходят, когда key
или index
используются для связывания или последовательность списка/словаря неверна или не существует.
Здесь есть два вида исключений:
- Ошибка индекса (
IndexError
); - Ошибка ключа (
KeyError
);
Ошибка ключа
Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError
.
try:
a = {1:'a', 2:'b', 3:'c'}
print(a[4])
except LookupError:
print("Исключение KeyError.")
else:
print("Успех, нет ошибок!")
Исключение KeyError.
Ошибка индекса
Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).
try:
a = ['a', 'b', 'c']
print(a[4])
except LookupError:
print("Исключение IndexError, индекс списка вне диапазона.")
else:
print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.
Ошибка памяти (MemoryError)
Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.
Ошибка имени (NameError)
Ошибка имени возникает, когда локальное или глобальное имя не находится.
В следующем примере переменная ans
не определена. Результатом будет ошибка NameError
.
try:
print(ans)
except NameError:
print("NameError: переменная 'ans' не определена")
else:
print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена
Ошибка выполнения (Runtime Error)
Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented
. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.
class BaseClass(object):
"""Опередляем класс"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
# функция ничего не делает
raise NotImplementedError(self.__class__.__name__ + '.do_something')
class SubClass(BaseClass):
"""Реализует функцию"""
def do_something(self):
# действительно что-то делает
print(self.__class__.__name__ + ' что-то делает!')
SubClass().do_something()
BaseClass().do_something()
SubClass что-то делает!
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
in
14
15 SubClass().do_something()
---> 16 BaseClass().do_something()
in do_something(self)
5 def do_something(self):
6 # функция ничего не делает
----> 7 raise NotImplementedError(self.__class__.__name__ + '.do_something')
8
9 class SubClass(BaseClass):
NotImplementedError: BaseClass.do_something
Ошибка типа (TypeError)
Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.
В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.
try:
a = 5
b = "PythonRu"
c = a + b
except TypeError:
print('Исключение TypeError')
else:
print('Успех, нет ошибок!')
Исключение TypeError
Ошибка значения (ValueError)
Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.
В этом примере встроенная операция float
получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.
try:
print(float('PythonRu'))
except ValueError:
print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'
Пользовательские исключения в Python
В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.
Это можно сделать, создав новый класс, который будет наследовать из класса Exception
в Python.
class UnAcceptedValueError(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
Total_Marks = int(input("Введите общее количество баллов: "))
try:
Num_of_Sections = int(input("Введите количество разделов: "))
if(Num_of_Sections < 1):
raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
print("Полученная ошибка:", e.data)
Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1
В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.
Недостатки обработки исключений в Python
У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.
Дальше пример, где модуль Python timeit
используется для проверки времени исполнения 2 разных инструкций. В stmt1
для обработки ZeroDivisionError
используется try-except, а в stmt2
— if
. Затем они выполняются 10000 раз с переменной a=0
. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1
с обработкой исключений занимает больше времени чем stmt2
, который просто проверяет значение и не делает ничего, если условие не выполнено.
Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.
import timeit
setup="a=0"
stmt1 = '''
try:
b=10/a
except ZeroDivisionError:
pass'''
stmt2 = '''
if a!=0:
b=10/a'''
print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))
time= 0.003897680000136461
time= 0.0002797570000439009
Выводы!
Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.
Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try
выискивает исключения, а except
их обрабатывает.
Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.
In this article, we will be discussing the TypeError: “int” Object is not callable exception. We will also be through solutions to this problem with example programs.
Why Is This Error Raised?
- “int” is used as a variable name.
- Arithmetic Operator not provided when calculating integers.
- Placing parentheses after a number
Using int As A Variable, Name
Variable declaration using in-built names or functions is a common mistake in rookie developers. An in-built name is a term with its value pre-defined by the language itself. That term can either be a method or an object of a class.
int
is an in-built Python keyword. As we discussed, it is not advisable to use pre-defined names as variable names. Although using a predefined name will not throw any exception, the function under the name will no longer be re-usable.
Let’s refer to the following example:
myNums = [56,13,21,54] sum = 0 sum = sum(myNums) print("sum of myNums list: ", sum)
Output and Explanation
- Variable
myNum
s is a list of 4 integers. - A variable
sum
is initialized with the value 0 - The sum of
myNums
list is calculated usingsum()
function and stored insum
variable. - Results printed.
What went wrong here? In step 2, we initialize a variable sum
with a value of 0. In Python, sum
is a pre-defined function. When were try to use the sum function in step 3, it fails. Python only remembers sum
as a variable since step 2. Therefore, sum()
has lost all functionality after being declared as a variable.
Solution
Instead of using sum
as a variable declaration, we can use more descriptive variable names that are not pre-defined (mySum
, mySum
, totalSum
). Make sure to follow PEP 8 naming conventions.
myNums = [56,13,21,54] totalSum = 0 totalSum= sum(myNums) print("sum of myNums list: ", totalSum)
Correct Output
sum of myNums list: 144
Arithmetic Operator Not Provided When Calculating Integers
Failing to provide an arithmetic operator in an equation can lead to TypeError: “int” object is not callable. Let’s look at the following example:
prices = [44,54,24,67] tax = 10 totalPrice = sum(prices) taxAmount = totalPrice(tax/100) print("total taxable amounr: ", taxAmount)
Output / Explanation
- List of integers stored in the variable
prices
- Tax percentage set to
10
- Total price calculated and stored in
totalPrice
- Total Taxable amount calculated.
- Final result printed.
To calculate the taxable amount, we must multiply totalPrice
with tax percentage. In step 4, while calculating taxAmount
, the *
operator is missing. Therefore, this gives rise to TypeError: "int" Object Is Not Callable
Solution
Denote all operators clearly.
prices = [44,54,24,67] tax = 10 totalPrice = sum(prices) taxAmount = totalPrice*(tax/100) print("total taxable amounr: ", taxAmount)
total taxable amount: 18.900000000000002
Recommended Reading | [Solved] TypeError: ‘str’ object is not callable
Placing Parentheses After an Integer
Let’s look at the following code:
Output / Explanation
It is syntactically wrong to place parentheses following an integer. Similar to the previous section, It is vital that you ensure the correct operators.
Solution
Do not use brackets after a raw integer. Denote correct operators.
cursor.rowcount() TypeError: “int” Object Is Not Callable
Let’s look at the following code:
sample ="select * from myTable" ... ... ... .... self.cur = self.con.cursor() self.cur.execute(sample) print(self.cur.rowcount())
Error Output
TypeError: 'int' object is not callable
Solution
According to the sqlite3 documentation provided by Python, .rowcount
is an attribute and not a function. Thereby remove the parenthesis after .rowcount
.
sample ="select * from myTable" ... ... ... .... self.cur = self.con.cursor() self.cur.execute(sample) print(self.cur.rowcount)
Let’s refer to the following code.
contours,hierarchy = cv2.findContours( thresh,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE ) ... ... ... ... if (hierarchy.size() > 0): numObj =hierarchy.size()
Error Output
if (hierarchy.size() > 0):
TypeError: 'int' object is not callable
Solution
The hierarchy
object returned is a numpy.ndarray
object. You should also note that the numpy.ndarray.size
attribute is an integer, not a method. Therefore, they cause the exception.
if event.type == pygame.quit() TypeError: ‘int’ Object Is Not Callable
Let’s refer to the example code to move an image:
import pygame import sys pygame.init() ... ... ... while True: for i in pygame.event.get(): if i.type() == pygame.QUIT: sys.exit() ... ...
Error Output
if i.type() == pygame.QUIT:
TypeError: 'int' object is not callable
Solution
The condition statement should be:
if i.type == pygame.QUIT:
Instead of the current:
if i.type() == pygame.QUIT:
Please note that type
is a member of the class Event
, not a function. Therefore, it is not required to pass parenthesis.
TypeError: ‘int’ Object Is Not Callable Datetime
Let’s refer to the following code:
from datetime import * ... ... ... for single_date in daterange(start_date, end_date): if single_date.day() == 1 and single_date.weekday() == 6: sundays_on_1st += 1
Error Output
TypeError: 'int' object is not callable
Solution
.day
is not a function but an attribute. Therefore passing parenthesis should be avoided.
from datetime import * ... ... ... for single_date in daterange(start_date, end_date): if single_date.day == 1 and single_date.weekday() == 6: sundays_on_1st += 1
FAQs
How do I fix TypeError int object is not callable?
You can fix this error by not using “int” as your variable name. This will avoid the cases where you want to convert the data type to an integer by using int().
What does TypeError int object is not callable mean?
Object not callable simply means there is no method defined to make it callable. Usually, parenthesis is used to call a function or object, or method.
Conclusion
We have looked at the exception TypeError: ‘int’ Object Is Not Callable. This error mostly occurs due to basic flaws in the code written. Various instances where this error appears have also been reviewed.
Other Errors You Might Get
-
“Other Commands Don’t Work After on_message” in Discord Bots
●February 5, 2023
-
Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials
by Rahul Kumar Yadav●February 5, 2023
-
[Resolved] NameError: Name _mysql is Not Defined
by Rahul Kumar Yadav●February 5, 2023
-
Troubleshooting “Cannot import name ‘escape’ from ‘jinja2′” Error
by Rahul Kumar Yadav●February 5, 2023
In Python, integers are single values. You cannot access elements in integers like you can with container objects. If you try to change an integer in-place using the indexing operator [], you will raise the TypeError: ‘int’ object does not support item assignment.
This error can occur when assigning an integer to a variable with the same name as a container object like a list or dictionary.
To solve this error, check the type of the object before the item assignment to make sure it is not an integer.
This tutorial will go through how to solve this error and solve it with the help of code examples.
Table of contents
- TypeError: ‘int’ object does not support item assignment
- Example
- Solution
- Summary
TypeError: ‘int’ object does not support item assignment
Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type.
The part 'int' object
tells us that the error concerns an illegal operation for integers.
The part does not support item assignment
tells us that item assignment is the illegal operation we are attempting.
Integers are single values and do not contain elements. You must use indexable container objects like lists to perform item assignments.
This error is similar to the TypeError: ‘int’ object is not subscriptable.
Example
Let’s look at an example where we define a function that takes a string holding a phrase, splits the string into words and then stores the counts of each word in a dictionary. The code is as follows:
def word_count(string): # Define empty dictionary word_dict = {} # Split string into words using white space separator words = string.split() # For loop over words for word in words: print(word) # Try code block: if word already in dictionary, increment count by 1 try: if word_dict[word]: value = word_dict[word] word_dict = value + 1 # Except code block: if word not in dictionary, value is 1 except: word_dict[word] = 1 return word_dict
We will then use the input()
method to take a string from the user as follows:
string = input("Enter a string: ") word_count(string)
Let’s run the code to see what happens:
Enter a string: Python is really really fun to learn Python is really really fun TypeError Traceback (most recent call last) <ipython-input-15-eeabf619b956> in <module> ----> 1 word_count(string) <ipython-input-9-6eaf23cdf8cc> in word_count(string) 9 word_dict = value + 1 10 except: ---> 11 word_dict[word] = 1 12 13 return word_dict TypeError: 'int' object does not support item assignment
The error occurs because we set word_dict
to an integer in the try
code block with word_dict = value + 1
when we encounter the second occurrence of the word really
. Then when the for loop moves to the next word fun
which does not exist in the dictionary, we execute the except
code block. But word_dict[word] = 1
expects a dictionary called word_dict
, not an integer. We cannot perform item assignment on an integer.
Solution
We need to ensure that the word_dict variable remains a dictionary throughout the program lifecycle to solve this error. We need to increment the value of the dictionary by one if the word already exists in the dictionary. We can access the value of a dictionary using the subscript operator. Let’s look at the revised code:
def word_count(string): # Define empty dictionary word_dict = {} # Split string into words using white space separator words = string.split() # For loop over words for word in words: print(word) # Try code block: if word already in dictionary, increment count by 1 try: if word_dict[word]: value = word_dict[word] word_dict[word] = value + 1 # Except code block: if word not in dictionary, value is 1 except: word_dict[word] = 1 return word_dict
Enter a string: Python is really really fun to learn
Python is really really fun to learn {'Python': 1, 'is': 1, 'really': 2, 'fun': 1, 'to': 1, 'learn': 1}
The code runs successfully and counts the occurrences of all words in the string.
Summary
Congratulations on reading to the end of this tutorial. The TypeError: ‘int’ object does not support item assignment occurs when you try to change the elements of an integer using indexing. Integers are single values and are not indexable.
You may encounter this error when assigning an integer to a variable with the same name as a container object like a list or dictionary.
It is good practice to check the type
of objects created when debugging your program.
If you want to perform item assignments, you must use a list or a dictionary.
For further reading on TypeErrors, go to the articles:
- How to Solve Python TypeError: ‘str’ object does not support item assignment
- How to Solve Python TypeError: ‘tuple’ object does not support item assignment
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Table of Contents
Hide
- What is Subscriptable in Python?
- How do you make an object Subscriptable?
- How to Fix TypeError: ‘int’ object is not subscriptable?
- Solution
- Conclusion
In Python, we use Integers to store the whole numbers, and it is not a subscriptable object. If you treat an integer like a subscriptable object, the Python interpreter will raise TypeError: ‘int’ object is not subscriptable.
In this tutorial, we will learn what ‘int’ object is is not subscriptable error means and how to resolve this TypeError in your program with examples.
“Subscriptable” means that you’re trying to access an element of the object. The elements are usually accessed using indexing since it is the same as a mathematical notation that uses actual subscripts.
How do you make an object Subscriptable?
In Python, any objects that implement the __getitem__
method in the class definition are called subscriptable objects, and by using the __getitem__
method, we can access the elements of the object.
For example, strings, lists, dictionaries, tuples are all subscriptable objects. We can retrieve the items from these objects using indexing.
Note: Python doesn't allow to subscript the NoneType if you do Python will raise TypeError: 'NoneType' object is not subscriptable
How to Fix TypeError: ‘int’ object is not subscriptable?
Let us take a small example to read the birth date from the user and slice the day, months and year values into separate lines.
birth_date = int(input("Please enter your birthdate in the format of (mmddyyyy) "))
birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]
print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)
If you look at the above program, we are reading the user birth date as an input parameter in the mmddyy format.
Then to retrieve the values of the day, month and year from the user input, we use slicing and store it into a variable.
When we run the code, Python will raise a TypeError: ‘int’ object is not subscriptable.
Please enter your birthdate in the format of (mmddyyyy) 01302004
Traceback (most recent call last):
File "C:PersonalIJSCodemain.py", line 3, in <module>
birth_month = birth_date[0:2]
TypeError: 'int' object is not subscriptable
Solution
In our example, we are reading the birth date as input from the user and the value is converted to an integer.
The integer values cannot be accessed using slicing or indexing, and if we do that, we get the TypeError.
To solve this issue, we can remove the int() conversion while reading the input from the string. So now the birth_date will be of type string, and we can use slicing or indexing on the string variable.
Let’s correct our example and run the code.
birth_date = input("Please enter your birthdate in the format of (mmddyyyy) ")
birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]
print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)
Output
Please enter your birthdate in the format of (mmddyyyy) 01302004
Birth Month: 01
Birth Day: 30
Birth Year: 2004
The code runs successfully since the int() conversion is removed from the code, and slicing works perfectly on the string object to extract a day, month and year.
Conclusion
The TypeError: ‘int’ object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects.
The issue can be resolved by removing any indexing or slicing to access the values of the integer object. If you still need to perform indexing or slicing on integer objects, you need to first convert that into strings or lists and then perform this operation.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
In Python, we can use the parenthesis »
()
» for multiple purposes such as we can use them as small brackets to compute mathematical computation
e.g (a+b)*c
, define a tuple
e.g a=(1,2,3)
or use them in the function definition and calling
e.g function_name()
.
But if we mistreat the mathematical computation parenthesis usages with function calling parenthesis, the Python interpreter throws the
TypeError: ‘int’ object is not callable
error.
In this Python error guide, we will walk through this Python error and discuss why it raises and how to solve it. We will also discuss some examples that will give you a better understanding of this Python error. So let’s get started.
The Error statement is itself divided into two parts
-
Error Type
TypeError
:
The TypeError occurs in the Python program when we mishandle the property of one data type with another. -
Error Message
int object is not callable
:
This is the error message, that is telling us we are trying to call a function using an integer variable name.
Why this Error Occur in Python
According to the Python syntax, to call a function, we need to write the function name followed by the parenthesis.
Example
def my_function():
print("This is a function")
# call function
my_function()
But if, instead of the function name, we put the parenthesis after an integer value or variable, we receive the
"TypeError: ‘int’ object is not callable"
error.
Example
def my_function():
print("This is a function")
number = 20
# parenthesis after a integer variable
number()
Output
Traceback (most recent call last):
File "main.py", line 6, in <module>
number()
TypeError: 'int' object is not callable
Common Scenario
There are two major common cases when most new Python learners commit this error.
- Use the same name for function and integer variables.
- Forget to put the multiplication operator while performing a mathematical calculation.
Scenario 1: Using the same name for int variable and function.
The most common scenario when Python learners commit this mistake is when they use the same name for the function and the integer variable.
Let’s create an example where we want to calculate the total sum of our bill list. And we use the Python inbuilt function called
sum()
to calculate the sum of the list and use the same variable name to store the total sum.
Example
bill = [12, 34, 23, 53, 10, 9]
# total integer sum
sum = 0
# using the inbuilt Python sum method
sum = sum(bill)
print("The total bill is: ",sum)
Output
Traceback (most recent call last):
File "main.py", line 7, in <module>
sum = sum(bill)
TypeError: 'int' object is not callable
Break the code
We are getting this error because, in line 4, we defined a new integer variable by the name
sum = 0
. Now for the complete program, Python will treat the sum as an integer value(until we change it).
But in line 7, we are trying to compute the sum of the
bill
list using the Python
sum()
function, but now Python is confused between the names, so it will treat the
sum
as the integer object, not as an inbuilt function, and throw the
TypeError 'int' object is not callable
.
Solution 1
The solution to the above problem is very simple. We just need to change the integer
sum
object name to another name, so the inbuilt function can be invoked.
Solution
bill = [12, 34, 23, 53, 10, 9]
# total integer
total = 0
# using the inbuilt Python sum method
total = sum(bill)
print("The total bill is: ",total)
Output
The total bill is: 141
Scenario 2: Forget to put the multiplication operator while performing a mathematical calculation
In mathematics, we use brackets to represent a mathematical expression. There we can use the () brackets to represent the multiplication operation between the numbers inside and outside the bracket.
for instance (in mathematics)
2(3+4) = 14
But this syntax is invalid in Python. In Python, we need to explicitly specify the mathematic operator between the number and opening & closing parenthesis. for instance, if we rewrite the above expression in Python, we have to write it in this manner.
In Python
>>>2*(3+4)
14
Example
a = 2
b = 3
c = 4
# error
result = a(b+c)
print(result)
Output
Traceback (most recent call last):
File "main.py", line 6, in <module>
result = a(b+c)
TypeError: 'int' object is not callable
Break the code
In the above example
a
,
b
and
c
all are integer, but in line 6, we are missing the * operator between the
a
and opening parenthesis
(
that’s why Python is calling
a
as a function that leads to the
TypeError: 'int' object is not callable
error.
Solution 3
The solution for the above error is very simple, we just need to specify the
*
multiplication operator between
a
and
(
.
solution 2
a = 2
b = 3
c = 4
# solved
result = a+(b+c)
print(result)
Output
14
Conclusion
In this Python tutorial, we learned what is
TypeError: ‘int’ object is not callable
Error in Python and how to solve it. If you look closely at the error message, you will get an overall idea of what this error is all about. This error generally occurs in Python when we try to call a function using an integer name. To solve this problem, all you need to do is remove the parenthesis after the integer variable name.
If you are still getting this error in your Python program, you can comment your code and query in the comment section. We will try to help you in debugging.
People are also reading:
-
Delete Emails in Python
-
Python typeerror: ‘str’ object is not callable Solution
-
Python Numpy Array Tutorial
-
Python TypeError: ‘method’ object is not subscriptable Solution
-
Numpy Dot Product
-
Python Error: TypeError: ‘tuple’ object is not callable Solution
-
Python Check If File or Directory Exists
-
Python SyntaxError: unexpected EOF while parsing Solution
-
Online Python Compiler
-
Python ‘numpy.ndarray’ object is not callable Solution