Typeerror module object is not callable питон ошибка

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:ProjectsTryoutsPython 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.

There are many in-built functions in Python, offering a variety of operations. All these functions are within modules or libraries. So, if you want to use a function that is within a module, you need to specify the module within the program where the function resides. Modules are included in Python programs using the import statement. For example, 

import math

This statement will include the math module within your program. You can use the functions such as factorial(), floor() and fabs() within this module. But if you try using a function with name math(), the compiler will be confused. It will throw an error called TypeError ‘module’ object is not callable in Python.
Here, we will focus on a solution to this problem.       

In Python, all inbuilt function is provided by modules, therefore to use any function within the module, we need to include that module in our code file.

Note: Module is the collection of code library in a categorical manner.

What is TypeError ‘module’ object is not callable in Python

This error statement TypeError: ‘module’ object is not callable occurs when the user gets confused between Class name and Module name. The issue occurs in the import line while importing a module as module name and class name have the same name.

Cause of this Error

The error “TypeError: ‘module’ object is not callable” occurs when the python compiler gets confused between function name and module name and try to run a module name as a function.

Example:

# Import os Module

import os

os()

Output:

Traceback (most recent call last):

  File "call.py", line 4, in <module>

    os()

TypeError: 'module' object is not callable

In the above example, we have imported the module “os” and then try to run the same “os” module name as a function.

And as we can see In the module “os” there is no function with the name “os” therefore TypeError: ‘module’ object is not callable” is thrown.

TypeError 'module' object is not callable in Python

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.

There are many in-built functions in Python, offering a variety of operations. All these functions are within modules or libraries. So, if you want to use a function that is within a module, you need to specify the module within the program where the function resides. Modules are included in Python programs using the import statement. For example, 

import math

This statement will include the math module within your program. You can use the functions such as factorial(), floor() and fabs() within this module. But if you try using a function with name math(), the compiler will be confused. It will throw an error called TypeError ‘module’ object is not callable in Python.
Here, we will focus on a solution to this problem.       

In Python, all inbuilt function is provided by modules, therefore to use any function within the module, we need to include that module in our code file.

Note: Module is the collection of code library in a categorical manner.

What is TypeError ‘module’ object is not callable in Python

This error statement TypeError: ‘module’ object is not callable occurs when the user gets confused between Class name and Module name. The issue occurs in the import line while importing a module as module name and class name have the same name.

Cause of this Error

The error “TypeError: ‘module’ object is not callable” occurs when the python compiler gets confused between function name and module name and try to run a module name as a function.

Example:

# Import os Module

import os

os()

Output:

Traceback (most recent call last):

  File "call.py", line 4, in <module>

    os()

TypeError: 'module' object is not callable

In the above example, we have imported the module “os” and then try to run the same “os” module name as a function.

And as we can see In the module “os” there is no function with the name “os” therefore TypeError: ‘module’ object is not callable” is thrown.

TypeError 'module' object is not callable in Python

Example with Custom module and function

To explain this error, we will create a module and function with the same name.

File name: mymodule.py

Code:

def mymodule():

 myval='STechies'

 print(myval)

In the above code we have created a file name “mymodule.py” and in that file created a function with the name “mymodule”

We can see that the module name and the function name in the above code is the same.

File name: mycode.py

Code:

import mymodule

print(mymodule())

Output:

Traceback (most recent call last):

  File "mycode.py", line 3, in <module>

    print(mymodule())

TypeError: 'module' object is not callable

In the above code, we are trying to call a function named “mymodule” which is in module “mymodule”, due to the similar name of module and function and due to this our python compiler gets confused and throws the following error

TypeError: ‘module’ object is not callable

How to fix typeerror: ‘module’ object is not callable?

To fix this error, we need to change the import statement in “mycode.py” file and specify a specific function in our import statement.

Example:

from mymodule import mymodule

print(mymodule())

Output:

STechies

In the above code, we have imported “mymodule” function from “mymodule” module, so our compiler won’t get confused and can execute the function mymodule().

Понравилась статья? Поделить с друзьями:
  • Typeerror int object is not callable ошибка
  • Typeerror function object is not subscriptable ошибка
  • Typeerror failed to fetch ошибка
  • Type object is not subscriptable python ошибка
  • Type object has no attribute objects ошибка