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

В процессе работы с Python иногда возникает ошибка «TypeError: ‘module’ object is not callable». Эта ошибка обычно происходит, когда разработчик пытается вызвать

В процессе работы с Python иногда возникает ошибка «TypeError: ‘module’ object is not callable». Эта ошибка обычно происходит, когда разработчик пытается вызвать модуль, как функцию.

Пример ошибки:

import math

result = math(5)

В этом коде разработчик пытается вызвать модуль math как функцию, что невозможно и вызывает ошибку TypeError: 'module' object is not callable.

Причина ошибки:

Модули в Python — это файлы, содержащие Python код, которые можно импортировать в другие Python файлы. Они не являются функциями и не могут быть вызваны как функции. Вместо этого, модули предоставляют функции, переменные и классы, которые можно использовать в другом коде после импорта модуля.

Решение ошибки:

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

Исправленный пример:

import math

result = math.sqrt(5)

В этом коде вызывается функция sqrt() из модуля math, а не сам модуль math. Этот код не вызовет ошибку TypeError: 'module' object is not callable, так как вызывается функция, а не модуль.

В заключение, ошибка «TypeError: ‘module’ object is not callable» в Python обычно указывает на то, что разработчик пытается вызвать модуль, как функцию. Для решения этой ошибки необходимо вызвать функцию, класс или переменную из модуля, а не сам модуль.

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 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

Python throws TypeError: ‘module’ object is not callable when you get confused between the class name and module name. There are several reasons why this might happen while coding. Let’s look at each scenario, and the solution to fix the ‘module‘ object is not callable error.

You will get this error when you call a module object instead of calling a class or function inside that module object. In Python, a callable object must be a class or a function that implements the “__call__” method.

 Example 1 – Calling a built-in Python module as a function 

 The below code is a straightforward example of importing a socket module in Python, and after the import, we are accessing the module as a function. Since we use the same name and run the “socket” module name as a function, Python will throw TypeError: ‘module’ object is not callable.

#Importing the socket module in Python

import socket
#Calling the os module as a function
s = socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
 

Output

Traceback (most recent call last):
  File "c:\Projects\Tryouts\Python Tutorial.py", line 2, in <module>
    s = socket(socket.AF_INET, socket.SOCK_STREAM)
TypeError: 'module' object is not callable

It mostly happens with developers who tend to get confused between the module name and the class names.

Solution 1 –  Instead of directly calling the module name, call the function using Modulename.FunctionName, which is defined inside the module.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
 

Solution 2 –  Another solution is to change the import statement, as shown below. Here the compiler will not get confused between the module name and the function name while executing the code.

from socket import *
 
s = socket(AF_INET, SOCK_STREAM)
print(s)

Output

<socket.socket fd=444, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>

Example 2 – Calling custom module as a function

Another scenario where we have a custom module as “namemodule” and using this as a function that leads to TypeError.

Below example we have created a file with namemodule.py

def namemodule():
 name='Chandler Bing'
 print(name)

In the second step we are trying to import the namemodule and calling it as a function which leads to TypeError.

import namemodule

print(namemodule())

Solution: Instead of importing the module, you can import the function or attribute inside the module to avoid the typeerror module object is not callable, as shown below.

from namemodule import namemodule

print(namemodule())

# Output
# Chandler Bing

Avatar Of Srinivas Ramakrishna

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.

Понравилась статья? Поделить с друзьями:
  • Module datetime has no attribute now ошибка
  • Modr клуб романтики ошибка
  • Modorganizer exe системная ошибка
  • Modloader при запуске ошибка
  • Modifier is disabled skipping apply blender ошибка