Module object is not callable python ошибка

Автор оригинала: Shubham Sayon.

Обзор

Цель: Цель этой статьи – обсудить и исправить TypeError: «Модуль» объект не вызывается в питоне. Мы будем использовать многочисленные иллюстрации и методы для решения проблемы упрощенным образом.

Пример 1. :

# Example of TypeError:'module' object is not callable
import datetime  # importing datetime module


def tell_date():  # Method for displaying today's date
    return datetime()


print(tell_date())

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 9, in 
    print(tell_date())
  File "D:/PycharmProjects/PythonErrors/rough.py", line 6, in tell_date
    return datetime()
TypeError: 'module' object is not callable

Теперь вышеупомянутый выход приводит нас к нескольким вопросам. Давайте посмотрим на них один за другим.

Типеррор является одним из наиболее распространенных исключений в Python. Вы столкнетесь с Исключение типа «Типерре» В Python всякий раз, когда есть несоответствие в типов объектов в определенной работе. Это обычно происходит, когда программисты используют неверные или неподдерживаемые типы объектов в своей программе.

Пример: Посмотрим, что произойдет, если мы попытаемся объединить ул ...| объект с int объект:

# Concatenation of str and int object
string = 'Nice'
number = 1
print(string + number)

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 4, in 
    print(string + number)
TypeError: can only concatenate str (not "int") to str

Объяснение:

В приведенном выше примере мы можем ясно видеть, что Исключение типа «Типерре» произошло потому, что мы можем только объединять ул ...| другому ул …| Объект и не к любому другому типу объекта (например, int , float , etc .)

  • « + «Оператор может объединить ул ...| (строки) объекты. Но в случае int (целые числа), он используется для добавления. Если вы хотите насильственно выполнять конкатенацию в приведенном выше примере, вы можете легко сделать это, напечатавшись на
  • int объект к ул …| тип.

📖 Читайте здесь: Как исправить JypeError: Список индексов должен быть целыми числами или ломтиками, а не «STR»?

Итак, от предыдущих иллюстраций у вас есть четкое представление о Типеррор Отказ Но что делает исключение TypeError: «Модуль» объект не вызывается иметь в виду?

🐞 Типеррера: «Модуль» объект не вызывается

Python обычно предоставляет сообщение с поднятыми исключениями. Таким образом, Исключение типа «Типерре» Есть сообщение Объект «Модуль» не является Callable , что означает, что вы пытаетесь вызвать объект модуля вместо класса или объекта функции внутри этого модуля.

Это происходит, если вы попытаетесь вызвать объект, который не вызывается. Callable объект может быть классом или методом, который реализует __вызов__ «Метод. Причина этого может быть (1) Путаница между именем модуля и именем класса/функции внутри этого модуля или (2) неверный класс или вызов функции.

Причина 1 : Давайте посмотрим на примере первой причины, то есть Путаница между именем модуля и именем класса/функции Отказ

  • Пример 2 : Рассмотрим следующий пользовательский модуль – решить .py :
# Defining solve Module to add two numbers
def solve(a, b):
    return a + b

Теперь давайте попробуем импортировать вышеуказанный пользовательский модуль в нашей программе.

import solve

a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print(solve(a, b))

Выход:

Enter first number: 2
Enter second number: 3
Traceback (most recent call last):
  File "main.py", line 6, in 
    print(solve(a, b))
TypeError: 'module' object is not callable

Объяснение: Здесь пользователь запутался между именем модуля и именем функции, так как они оба являются точно такими же, I.e. ‘ решить ‘.

Причина 2 : Теперь, давайте обсудим еще один пример, который демонстрирует следующую причину, то есть неправильный класс или звонок функции.

Если мы выполним неверный импорт или функциональную операцию вызова, то мы, вероятно, снова станем исключением. Ранее в примере, приведенном в обзоре, мы сделали неверный вызов, позвонив datetime Объект модуля вместо объекта класса, который поднял TypeError: «Модуль» объект не вызывается исключением.

Теперь, когда мы успешно прошли причины, которые приводят к возникновению нашей проблемы, давайте найдем решения для его преодоления.

📚 Как исправить TypeError: «Модуль» объект не вызывается ?

🖊️ Метод 1: Изменение оператора «Импорт»

Для исправления первой проблемы, которая является путаницей между именем модуля и именем класса/функции, позвольте нам пересмотреть Пример 2 Отказ Здесь модульрешить У также есть Метод назван «RELVE» , таким образом создавая путаницу.

Чтобы исправить это, мы можем просто изменить оператор импорта, импортируя конкретную функцию внутри этого модуля или просто импортируя все классы и методы внутри этого модуля.

# importing solve module in Example 2
from solve import solve

a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print(solve(a, b))

Выход:

Enter first number: 2
Enter second number: 3
5

📝 Примечание:

  • Импорт всех классов и методов рекомендуется только в том случае, если размер импортируемого модуля небольшой, поскольку он может повлиять на временную и космическую сложность программы.
  • Вы также можете использовать псевдоним, используя подходящее имя, если у вас все еще есть путаница.
    • Например: – от решающего импорта решить как соль

🖊️ Метод 2: Использование. (Точка) нотация для доступа к классам/методам

Есть еще одно решение для той же проблемы. Вы можете получить доступ к атрибутам, классам или методам модуля, используя «.» Оператор. Поэтому вы можете использовать то же самое, чтобы исправить нашу проблему.

Давайте попробуем это снова на нашем примере 2.

# importing solve module in Example 2
import solve

a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print(solve.solve(a, b))

Выход:

Enter first number: 2
Enter second number: 3
5

🖊️ Метод 3: Реализация правильного вызова класса или функции

Теперь давайте обсудим решение второй причине нашей проблемы, то есть, если мы выполним неверный класс или вызов функции. Любая ошибка в реализации вызова может привести к тому, что может вызвать Ошибки в программе. Пример 1 имеет точно такую же проблему неправильного вызова функции, который поднял исключение.

Мы можем легко решить проблему, заменив неверное оператор вызовов с помощью правильного, как показано ниже:

import datetime  # importing datetime module
def tell_date():  # Method for displaying today's date
    return datetime.date.today()
print(tell_date())

Выход:

💰 Бонус

Вышеупомянутое Типеррор происходит из-за многочисленных причин. Давайте обсудим некоторые из этих ситуаций, которые приводят к возникновению аналогичного вида Типеррор Отказ

✨ JypeError ISERROR: объект «Список» не вызывается

Эта ошибка возникает, когда мы пытаемся вызвать объект «списка», а вы используете «()» вместо использования «[]».

Пример:

collection = ['One', 2, 'three']
for i in range(3):
    print(collection(i))  # incorrect notation

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 3, in 
    print(collection(i))  # incorrect notation
TypeError: 'list' object is not callable

Решение: Чтобы исправить эту проблему, нам нужно использовать правильный процесс доступа к элементам списка I.e, используя «[]» (квадратные скобки). Так просто! 😉.

collection = ['One', 2, 'three']
for i in range(3):
    print(collection[i])  # incorrect notation

Выход:

✨ Типеррера: «INT» Объект не Callable

Это еще одна общая ситуация, когда пользователь призывает int объект и заканчивается с Типеррор Отказ Вы можете столкнуться с этой ошибкой в сценариях, таких как следующее:

Объявление переменной с именем функции, которая вычисляет целочисленные значения

Пример:

# sum variable with sum() method
Amount = [500, 600, 700]
Discount = [100, 200, 300]
sum = 10
if sum(Amount) > 5000:
    print(sum(Amount) - 1000)
else:
    sum = sum(Amount) - sum(Discount)
    print(sum)

Выход:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/rough.py", line 5, in 
    if sum(Amount)>5000:
TypeError: 'int' object is not callable

Решение: Чтобы исправить эту проблему, мы можем просто использовать другое имя для переменной вместо сумма Отказ

#sum variable with sum() method
Amount = [500, 600, 700]
Discount = [100, 200, 300]
k = 10
if sum(Amount)>5000:
    print(sum(Amount)-1000)
else:
    k = sum(Amount)-sum(Discount)
    print(k)

Выход:

Вывод

Мы наконец достигли конца этой статьи. Фу! Это было некоторое обсуждение, и я надеюсь, что это помогло вам. Пожалуйста, Подписаться и Оставайтесь настроиться Для более интересных учебных пособий.

Спасибо Anirban Chatterjee Для того, чтобы помочь мне с этой статьей!

  • Вы хотите быстро освоить самые популярные Python IDE?
  • Этот курс приведет вас от новичка к эксперту в Пычарме в ~ 90 минут.
  • Для любого разработчика программного обеспечения имеет решающее значение для освоения IDE хорошо, писать, тестировать и отлаживать высококачественный код с небольшим усилием.

Присоединяйтесь к Pycharm MasterClass Сейчас и мастер Pycharm на завтра!

Я профессиональный Python Blogger и Content Creator. Я опубликовал многочисленные статьи и создал курсы в течение определенного периода времени. В настоящее время я работаю полный рабочий день, и у меня есть опыт в областях, таких как Python, AWS, DevOps и Networking.

Вы можете связаться со мной @:

  • Заработка
  • Linkedin.

I had this error when I was trying to use optuna (a library for hyperparameter tuning) with LightGBM. After an hour struggle I realized that I was importing class directly and that was creating an issue.

import lightgbm as lgb

def LGB_Objective(trial):
        parameters = {
            'objective_type': 'regression',
            'max_depth': trial.suggest_int('max_depth', 10, 60),
            'boosting': trial.suggest_categorical('boosting', ['gbdt', 'rf', 'dart']),
            'data_sample_strategy': 'bagging',
            'num_iterations': trial.suggest_int('num_iterations', 50, 250),
            'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0),
            'reg_alpha': trial.suggest_float('reg_alpha', 0.01, 1.0), 
            'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 1.0)
            }
        
        '''.....LightGBM model....''' 
        model_lgb = lgb(**parameters)
        model_lgb.fit(x_train, y_train)
        y_pred = model_lgb.predict(x_test)
        return mse(y_test, y_pred, squared=True)

study_lgb = optuna.create_study(direction='minimize', study_name='lgb_regression') 
study_lgb.optimize(LGB_Objective, n_trials=200)

Here, the line model_lgb = lgb(**parameters) was trying to call the cLass itself.
When I digged into the __init__.py file in site_packages folder of LGB installation as below, I identified the module which was fit to me (I was working on regression problem). I therefore imported LGBMRegressor and replaced lgb in my code with LGBMRegressor and it started working.

enter image description here

You can check in your code if you are importing the entire class/directory (by mistake) or the target module within the class.

from lightgbm import LGBMRegressor

def LGB_Objective(trial):
        parameters = {
            'objective_type': 'regression',
            'max_depth': trial.suggest_int('max_depth', 10, 60),
            'boosting': trial.suggest_categorical('boosting', ['gbdt', 'rf', 'dart']),
            'data_sample_strategy': 'bagging',
            'num_iterations': trial.suggest_int('num_iterations', 50, 250),
            'learning_rate': trial.suggest_float('learning_rate', 0.01, 1.0),
            'reg_alpha': trial.suggest_float('reg_alpha', 0.01, 1.0), 
            'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 1.0)
            }
        
        '''.....LightGBM model....''' 
        model_lgb = LGBMRegressor(**parameters) #here I've changed lgb to LGBMRegressor
        model_lgb.fit(x_train, y_train)
        y_pred = model_lgb.predict(x_test)
        return mse(y_test, y_pred, squared=True)

study_lgb = optuna.create_study(direction='minimize', study_name='lgb_regression') 
study_lgb.optimize(LGB_Objective, n_trials=200)

Когда вы смешиваете имена классов и модулей, Python возвращает объект TypeError:’module’, который нельзя вызывать. Во время кодирования это может произойти по многим причинам. Чтобы понять, что означает «объект не вызывается», мы должны сначала понять, что такое вызываемый объект Python. Как видно из названия, вызываемый объект — это то, что можно вызвать. Просто используйте встроенный метод callable() и отправьте ему объект, чтобы узнать, доступен ли он для вызова.

Вы когда-нибудь осознавали, что во время выполнения кода Python объект TypeError недоступен? Мы будем работать вместе, чтобы выяснить, почему это происходит. Когда объект, который нельзя вызывать, вызывается с использованием круглых скобок (), интерпретатор Python вызывает «TypeError», т. е. объект не является вызываемой ошибкой. Это может произойти, если вы случайно используете круглые скобки (), а не квадратные скобки [] для извлечения элементов списка. Мы покажем вам несколько сценариев, в которых возникает эта ошибка, а также то, что вы можете сделать, чтобы ее исправить. Ищем проблему! Но что это значит, когда объект не вызывается?

Когда вы вызываете модуль во время написания кода, это может происходить по многим причинам. Чаще всего, когда вы вызываете объект, а не класс или функцию в этом модуле, вы получите эту ошибку. Давайте рассмотрим каждый случай и то, как разрешить «объект модуля» — не вызываемую проблему.

Пример 1:

В нашем первом примере мы будем использовать функцию для вызова встроенного модуля Python. В приведенном ниже коде показано, как импортировать модуль сокета в Python и как впоследствии использовать его как функцию. Поскольку мы используем аналогичное имя для модуля и выполняем модуль «сокет» в качестве метода, Python вызовет «TypeError: объект модуля не вызывается».

Импортироватьразъем

а =разъем(разъем.AF_INET,разъем.SOCK_STREAM)

Распечатать(а)

https: lh5.googleusercontent.comi6rWc8iuxNibZx0B7mT7lOHVcV_FEEyMhdmG4uBLXK2ORbD5TEW5FzdVYVoMl9d6lCgdM1ojyhr1Px8ddSvALQ-wuK074EMzE1iIwPf-oVw8zSHP0SzabJ6H3Xsf7FwemiFwemi

Вот экран результатов, который показывает сгенерированную ошибку. Это наиболее распространено среди разработчиков, которые путаются между именами модулей и именами классов.

https: lh6.googleusercontent.comik25daTmzEAbGM6xNPqr4PqTTACZUM9sB4H4w09rxwnjgTGZjkvW6HR0zkvX9TXRz3NPIW2wHGA3TIp_WIVPuNETPJTuHS0MnL59mBYVkZV4Rbf5igzuInwMSwcr29mbS0t_8OZ3

Вот некоторые решения, которые можно применить. Первое решение — вызвать функцию с **Modulename вместо прямого вызова имени модуля. Внутри модуля есть функция с именем «FunctionName».

Импортироватьразъем

а =разъем.разъем(разъем.AF_INET,разъем.SOCK_STREAM)

Распечатать(а)

https: lh3.googleusercontent.comgaI6HdY3roJP9KUlHeHaumzd5P5vlSs1U2gUp3Wc6fBHVuYSO9F-uE-FB7S3Uzi_VvgmuBgwYTKhHj4dTCcUH7iQ55MO-1F2pER0LePUDLwYUg0JHhe0rDhHD1Gk-VxUIiCztyN

Вот результат. Как видите, код был успешно выполнен и ошибок не возникло.

https: lh4.googleusercontent.comrMXAtSK7zFsOVKK1erujFLS43H2BsKAywDaD2tcwNl-NIzhzS5B8Jaed3F_QdrvIyzrjKzYG3QXqVNwtkYGATguzcYjUj_JaHOIkCenYKn-cWMoe-VSZey70u1r-qrnyyNYAe3gC

Изменение оператора импорта, как показано ниже, является еще одним вариантом. При выполнении кода компилятор не будет путаться между именами модулей и функций.

Как видите, код успешно выполнился и ошибок не возникло.

отразъемИмпортировать *

а =разъем(AF_INET, SOCK_STREAM)

Распечатать(а)

https: lh5.googleusercontent.comtLO9ir8rZYKq-09xIjOGP_IODorvIyKjYPj4ZcmPgFINkkEFcP1S7_0JY16jP53Ckd80MfF4oJIxzAHFEfIw4AV0hqCir4yBYrj2dMpeIKISEuYifplv32xKjUyAHuHxJG8L9rs3

Здесь вы можете увидеть успешное выполнение приведенного выше кода.

https: lh4.googleusercontent.comglICo4CVgLHNQEMGvL61M1HH8Nhx4HI7VpMMDrcq2riYZXyevpdIOcop60nQxBVFf7dGAdWf3Qsf55T8Nvst8GZXADx4Vq-kIrNSmYG2Loctvo7bXTUOlvdH21FFMU5wlSIGURgw

Пример 2:

Другой пример — иметь пользовательский модуль с именем «mymodule» и использовать его как функцию, что приводит к ошибке TypeError. В приведенном ниже примере мы создали файл с именем «namemodule.py».

деф моймодуль();

н= «Питон является легко учить’

Распечатать()

https: lh6.googleusercontent.com_bcIS6M6wmrWrh4KJHmCeX8DEDk22sWk4vP-AtvC64POywH7GomMIhhwx87IiJ1epjGju9Fd_69sk1xmJy58xXHIOBPA1w5D0YXJm1jmTatcOwAdL02seManWw9fygak7LNN7LNN7

Мы пытаемся импортировать mymodule и вызывать его функцией на втором шаге, что приводит к TypeError.

Импортировать моймодуль

Распечатать(моймодуль())

https: lh4.googleusercontent.comaL_K-lLMQBcR9nS_xuIJCPBD5Jo1BoCAnCepsJhZKLD8vjJA7wHo6bNg67QFTcJCQ4ioIK5R2h70eqDfJHQCgWiqzniQ15SIUrJiS4DPontUfiVD8HSg3RvAQL88X09WHyFYoizU

Выполнение приведенного выше кода приводит к ошибке, как вы можете видеть на прикрепленном снимке экрана.

https: lh5.googleusercontent.comj9AZiZCQarRGBiQ85Qp28LooXb4UVkmP4QFefY-XWU3pfx9ml2yyi8gq9rIhltazEK3ZAV8Up4FgwHWjhGAYTLiXJC7BjdEPY7ZxmBcXvp7Rae5yg9yBER-Le_tEpkwQGU4sEr-m

Вот лучшее решение, которое вы можете применить, столкнувшись с подобной ситуацией. Таким образом, вместо того, чтобы импортировать модуль, можно импортировать функцию или функцию внутри модуля, как показано ниже, чтобы избежать ошибки.

от моймодуль Импортировать моймодуль

Распечатать(моймодуль())

https: lh4.googleusercontent.comb17Omwz3eH-QDNPNz5BVh1lKA4ukTK1xOlr2quWlF2VdSa6j2ucLe9ffx7_vZ1X1KCs-IWMYywo8ay8QYyqIwXbd4TMiCxWtZpoE2FfDgeU7G7OOhuTfdSyckGSIvuGwhZBGV0h

Здесь вы можете видеть, что после применения вышеуказанного решения код отлично выполняется и отображает следующий вывод.

https: lh6.googleusercontent.comBJwH_R8rf8A26jZNOOaur-lLv44afcdbFxxi8UsBHYN33IvsduveMu2KCZkDN6qmzIrwlWw33MFi89hhsNchNeE6yuQxd-OYrBu-PDU1l2V99c1Durm2k3ZUX2ESazsx7JiMAl-e

Пример 3:

Чтобы преобразовать значение в числовое значение, используйте функцию int(). Метод int() возвращает целочисленный объект, состоящий из числа или строки x, или 0, если параметры не указаны. Для преобразования в целочисленный объект необходимо указать число или строку. Значение параметра по умолчанию равно нулю.

инт=5

б =инт(Вход(‘Введите значение:’))

за я вдиапазон(1,инт):

Распечатать(я * 5)

https: lh3.googleusercontent.comCwToIMjE_PD3oEBscX-PXnLNBUPy-cwn4WW3IjbH1BaQmvF-gE1eokRZWKLovYFZuG9ARHu_IeyqeRTUF4xRfLv6YJ11l_y1PW_nmqAK-6i4AldHtUyibM-ql2csWWxlzSh7hpb

Ниже вы можете увидеть результат. Как видите, это выдает ошибку.

https: lh4.googleusercontent.comP_p3lk5Qdv6XWyImQbw6zarTvnxniCiv8TDFqnDBjN-IuweY6A9Kr1eLYsZsTomkGHhVAIPq-oXUEjmBGOar6w329_hYNIrV-jiypjx8kUHbpcXpCcxBwjShXwHU0iZv-OpXrRPp

Вы можете решить эту проблему, дав переменной другое имя. См. приведенный ниже код.

а =5

б =инт(Вход(‘Введите значение:’))

за я вдиапазон(1, а):

Распечатать(я * 5)

https: lh4.googleusercontent.comSY3RrCBbj0JHTA4-RxgFzejwhAgdC2t5DUg5Kano0c-f0pLJVvwQlzBmhS_UJ7wbdjr9Pn2xBcd2lZcL29uPD74pvhCJ8qDaoDZRqIWh6qjOS23V8-18EHcYt60YSfMLargo

Здесь изменения в коде дают правильный результат, как вы можете видеть ниже.

https: lh6.googleusercontent.compubvHscEPQoj2KHFn2AUXa_XwNGTTq6OAuIOI_Qt4457Mbk--hE1j0z6GycL_sgWNvm6Y5JV53vPr8WNn8ZyW2GG58ulhnNeqcYX_Lh7iLzRAUmxF-vh8wTk2vOlMUiW

Вывод:

Когда определенная операция выполняется над объектом неправильного типа, выдается ошибка TypeError. Когда вы пытаетесь получить доступ к модулю как к функции в вашей программе, вы получите сообщение об ошибке «TypeError: ‘module’ object is not callable». Это происходит, когда вы путаетесь между именем модуля и именем класса или метода в этом модуле. Если вы попытаетесь использовать оператор + для объединения строки и целочисленного объекта, вы получите TypeError, поскольку операция + не разрешена между объектами разных типов. В этом посте мы пролили свет на «TypeError: ‘Module’ Object Is Not Callable» и как это исправить в ваших программах на Python.

Python is well known for the different modules it provides to make our tasks easier. Not just that, we can even make our own modules as well., and in case you don’t know, any Python file with a .py extension can act like a module in Python. 

In this article, we will discuss the error called “typeerror ‘module’ object is not callable” which usually occurs while working with modules in Python. Let us discuss why this error exactly occurs and how to resolve it. 

Fixing the typeerror module object is not callable error in Python 

Since Python supports modular programming, we can divide code into different files to make the programs organized and less complex. These files are nothing but modules that contain variables and functions which can either be pre-defined or written by us. Now, in order to use these modules successfully in programs, we must import them carefully. Otherwise, you will run into the “typeerror ‘module’ object is not callable” error. Also, note that this usually happens when you import any kind of module as a function.  Let us understand this with the help of a few examples.

Example 1: Using an in-built module

Look at the example below wherein we are importing the Python time module which further contains the time() function. But when we run the program, we get the typeerror. This happens because we are directly calling the time module and using the time() function without referring to the module which contains it.

Python3

import time

inst = time()

print(inst)

Output

TypeError                                 Traceback (most recent call last)
Input In [1], in <module>
      1 import time
----> 2 inst = time()
      3 print(inst)

TypeError: 'module' object is not callable

From this, we can infer that modules might contain one or multiple functions, and thus, it is important to mention the exact function that we want to use. If we don’t mention the exact function, Python gets confused and ends up giving this error. 

Here is how you should be calling the module to get the correct answer:

Python3

from time import time

inst = time()

print(inst)

Output

1668661030.3790345

You can also use the dot operator to do the same as shown below-

Python3

import time

inst = time.time()

print(inst)

Output

1668661346.5753343

Example 2: Using a custom module

Previously, we used an in-built module. Now let us make a custom module and try importing it. Let us define a module named Product to multiply two numbers. To do that, write the following code and save the file as Product.py

Python3

def Product(x,y):

  return x*y

Now let us create a program where we have to call the Product module to multiply two numbers. 

Python3

import Product

x = int(input("Enter the cost: "))

y = int(input("Enter the price: "))

print(Product(a,b))

Output

Enter first number: 5
Enter second number: 10
Traceback (most recent call last):
  File "demo.py", line 6, in <module>
    print(Product(a, b))
TypeError: 'module' object is not callable

Why this error occurs this time? 

Well again, Python gets confused because the module as well as the function, both have the same name. When we import the module Product, Python does not know if it has to bring the module or the function. Here is the code to solve this issue:

Python3

from Product import Product

x = int(input("Enter the cost: "))

y = int(input("Enter the price: "))

print(Product(a,b))

Output

Enter the cost: 5
Enter the price: 10
50 

We can also use the dot operator to solve this issue. 

Python3

import Product

x = int(input("Enter the cost: "))

y = int(input("Enter the price: "))

print(Product.Product(a,b))

Output

Enter the cost: 5
Enter the price: 10
50 

Last Updated :
18 Apr, 2023

Like Article

Save Article

TypeError: module object is not callable [Python Error Solved]

In this article, we’ll talk about the «TypeError: ‘module’ object is not callable» error in Python.

We’ll start by defining some of the keywords found in the error message — module and callable.

You’ll then see some examples that raise the error, and how to fix it.

Feel free to skip the next two sections if you already know what modules are, and what it means to call a function or method.

What Is a Module in Programming?

In modular programming, modules are simply files that contain similar functionalities required to perform a certain task.

Modules help us separate and group code based on functionality. For example, you could have a module called math-ops.py which will only include code related to mathematical operations.

This makes easier to read, reuse, and understand the code. To use a module in a different part of your code base, you’d have to import it to gain access to all the functionalities defined in the module.

In Python, there are many built-in modules like os, math, time, and so on.

Here’s an example that shows how to use the math module:

import math

print(math.sqrt(25))
//5.0

As you can see above, the first thing we did before using the math module was to import it: import math.

We then made use of the module’s sqrt method which returns the square root of a number: math.sqrt(25).

All it took us to get the square root of 25 was two lines of code. In reality, the math module alone has over 3500 lines of code.

This should help you understand what a module is and how it works. You can also create your own modules (we’ll do that later in this article).

What Does callable Mean in the “TypeError: module object is not callable” Error?

In Python and most programming languages, the verb «call» is associated with executing the code written in a function or method.

Other similar terms mostly used with the same action are «invoke» and «fire».

Here’s a Python function that prints «Smile!» to the console:

def smile():
    print("Smile!")

If you run the code above, nothing will be printed to the console because the function smile is yet to be called, invoked, or fired.

To execute the function, we have to write the function name followed by parenthesis. That is:

def smile():
    print("Smile!")
    
smile()
# Smile!

Without the parenthesis, the function will not be executed.

Now you should understand what the term callable means in the error message: «TypeError: ‘module’ object is not callable».

What Does the “TypeError: module object is not callable” Error Mean in Python?

The last two sections helped us understand some of the keywords found in the «TypeError: ‘module’ object is not callable» error message.

To put it simply, the «TypeError: ‘module’ object is not callable» error means that modules cannot be called like functions or methods.

There are generally two ways that the «TypeError: ‘module’ object is not callable» error can be raised: calling an inbuilt or third party module, and calling a module in place of a function.

Error Example #1

import math

print(math(25))
# TypeError: 'module' object is not callable

In the example above, we called the math module (by using parenthesis ())  and passed 25 as a parameter hoping to perform a particular math operation: math(25). But we got the error.

To fix this, we can make use of any math method provided by the math module. We’ll use the sqrt method:

import math

print(math.sqrt(25))
# 5.0

Error Example #2

For this example, I’ll create a module for calculating two numbers:

# add.py

def add(a,b):
    print(a+b)
    

The name of the module above is add which can be derived from the file name add.py.

Let’s import the add() function from the add module in another file:

# main.py
import add

add(2,3)
# TypeError: 'module' object is not callable

You must be wondering why we’re getting the error even though we imported the module.

Well, we imported the module, not the function. That’s why.

To fix this, you have to specify the name of the function while importing the module:

from add import add

add(2,3)
# 5

We’re being specific: from add import add. This is the same as saying, «from the add.py module, import the add function».

You can now use the add() function in the main.py file.

Summary

In this article, we talked about the «TypeError: ‘module’ object is not callable» error in Python.

This error occurs mainly when we call or invoke a module as though it were a function or method.

We started by discussing what a module is in programming, and what it means to call a function – this helped us understand what causes the error.

We then gave some examples that showed the error being raised and how to fix it.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Module datetime has no attribute now ошибка
  • Modular voice chat ошибка переподключение
  • Modr клуб романтики ошибка
  • Modifier is disabled skipping apply blender ошибка
  • Modern warfare код ошибки