Module object is not callable error

File "C:UsersAdministratorDocumentsMibotoopsblinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable Why am I gett...

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)

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

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

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().

If you want to access a function belonging to a Python module, you have to specify the module within your program where the function resides. You can import modules using the import statement. If you try to call a module with the intent of calling a class, you will raise the error: TypeError: ‘module’ object is not callable.

This tutorial will go through the error in detail and an example scenario to solve the error.


Table of contents

  • TypeError: ‘module’ object is not callable
    • What is a TypeError?
    • What is a module?
  • Example
    • Solution
  • Summary

TypeError: ‘module’ object is not callable

What is a TypeError?

TypeError tells us that we are trying to perform an illegal operation for a specific Python data type. In this case, trying to call a Python module is not possible.

What is a module?

Modules are a vital part of Python that enable you to define functions, variables, and classes outside of your main program, which you can import. Modularizing your code allows you to categorize code blocks, making software development efficient. Any Python file is a module if it ends in the extension “.py“. You can use any Python source file as a module by executing an import state in another Python program. The syntax for import is as follows:

import module_1

You can import more than one module using the following syntax:

import module_1, module_2, module_3, ... module_N

You can also use the from… import statement to import specific attributes like a class from a module into your program. The from… import has the following syntax:

from module_name import name_1

You can import more than one attribute using the following syntax:

from module_name import name_1, name_2, name_3, ... name_N

If you want to import all attributes from a module, you can use the following statement

from module_name import *

If you try to call a module as if it were a function, for example:

module_name()

then you’ll raise the error: TypeError: ‘module’ object is not callable.

Example

Let’s define a module called electron that stores a class, whose attributes are the physical constants of the electron particle. We will write the class in a file called electron.py. Let’s look at the code:

class electron:

    def __init__(self):

        self.charge = -1

        self.mass = 0.51

        self.spin = 1/2

    def positron(self):

         self.charge = +1

         return self.charge

    def get_mass(self):

        return self.mass

The class defines the variables charge, mass, and spin, and two functions, positron() and get_mass(). Next, we will open a file called particle_test.py and write the following code:

import electron

ele = electron()

print(f'Electron charge = {ele.charge}')

print(f'Electron mass = {ele.mass} MeV')

The above code imports the electron module and attempts to use the electron module to get the charge and mass of the electron and print it to the console. Let’s run the code using the command python particle_test.py to see what happens:

Traceback (most recent call last):
  File "particle_test.py", line 3, in module
    ele = electron()
TypeError: 'module' object is not callable

The error occurs because we import the module but do not specify which attribute to use from the module.

Solution

We can solve this error in two ways. First, we can call the name of the class we want to reference instead of the function itself. In this case, the module and the class have the same name. Let’s look at the revised code:

import electron

ele = electron.electron()

print(f'Electron charge = {ele.charge}')

print(f'Electron mass = {ele.mass} MeV')                                          

In the above code, we create an instance of the electron class, which gives us access to its attributes. We then print the charge and the mass values to the console. Let’s run the code to see what happens:

Electron charge = -1
Electron mass = 0.51 MeV

Second, we can also the from… import statement to specify the class to import. Let’s look at the revised code:

from electron import electron

ele = electron()

print(f'Electron charge = {ele.charge}')

print(f'Electron mass = {ele.mass} MeV')

In the above code, we are still creating an instance of the electron class; we import the class directly into the program with the from… import statement. Let’s run the code to see what happens:

Electron charge = -1
Electron mass = 0.51 MeV

Both solutions result in the program successfully creating an electron object then printing the charge and mass values to the console.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘module’ object is not callable” occurs when you try to call a module as if it were a function. When working with modules, ensure that you correctly reference the functions, variables, and classes you want to access. If you’re going to call a function belonging to a module, you have to specify that function instead of calling the module.

For more reading on the ‘not callable’ TypeError, go to the article: How to Solve Python TypeError: ‘list’ object is not callable.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

The TypeError: ‘module’ object is not callable error occurs when python is confused between the class object and module. Python attempts to invoke a module as an instance of a class or as a function. This TypeError: ‘module’ object is not callable error occurs when class and module have the same name. The import statement imports the module name not the class name. Hence either the module object is not callable or the class object is not callable in python.

If a python file has the same name in both module name and class name, The import command imports the module name. When you try to access as a class instance, either the module is not callable or the class is not callable. Therefore, the error TypeError: ‘module’ object is not callable will be thrown.

The python module name is just a python file with the .py extension. The module is loaded with from keyword. The class in the file will be loaded using the import keyword. If both the module and class name are same and import statement is created without from keyword, then the python import would recognizes as a module name instead of the class name.

Condition for TypeError: ‘module’ object is not callable

There are three conditions that must be met for this error.

  • The python file name should be the same as that of python class name
  • The python class name should be imported using the keyword import
  • The python file is not loaded using the from keyword

Exception

The python interpreter will display the type error similar to the following

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    emp = Employee();
TypeError: 'module' object is not callable
[Finished in 0.1s with exit code 1]

Root Cause

If the name of the module is same as the class name and the import command is used to load the class without using from keyword for module reference, the python loads module object using import statement. If you try to access as a class instance, then the error TypeError: ‘module’ object is not callable will be thrown.

The code is written to invoke as a class or function but is defined as a module object by the python interpreter. The python interpreter throws this error TypeError: ‘module’ object is not callable, as it can not handle class methods within the module object.

How to reproduce this issue

The TypeError: ‘module’ object is not callable error occurs when the python file is available in the python path and the file name is included in the import statements. If the python imports a class as the name of the python file, this error can be reproduced.

The following example will create an error called “TypeError: ‘module’ object is not callable” as the name of the Employee class is the same as the name of the Employee.py file. The Employee class is imported into test.py. The python interpreter detects the Employee as a module and throws an error when the class object is created.

Employee.py

class Employee:
	id = 1

test.py

import Employee

emp = Employee();
print(emp.id);

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    emp = Employee();
TypeError: 'module' object is not callable
[Finished in 0.1s with exit code 1]

Solution 1

The python module should be loaded using the “from” keyword. If the module is loaded before the class is imported, the error “TypeError: ‘module’ object is not callable” will be resolved. The example below demonstrates how to load the module using the keyword “from.”

In the example below, Employee class is created in Employee.py python file. The instance of the Employee class is created in the test.py python file. If you import the Employee class, python interpreter identifies as you are importing Employee.py python file instead of Employee class. Therefore, you cannot call Employee() constructor as module does not have constructor.

Employee.py

class Employee:
	id = 1

test.py

from Employee import Employee

emp = Employee();
print(emp.id);

Output

1

Solution 2

The python detects the import as a module object. Therefore the name of the class is referenced along with the name of the module. The module name is prefixed with the name of the class. The python interpreter will use the module name to define the class, as shown in the example below.

Employee.py

class Employee:
	id = 1

test.py

import Employee

emp = Employee .Employee();
print(emp.id);

Output

1

Solution 3

The name of the python file and the name of the python class should be created differently so that the error can be easily detected. For example, the name of the python file should be created with a lower case. The python class has been created with the camel case. This error “TypeError: ‘module’ object is not callable” is quickly recognized and helps to prevent this error.

In the example below, the file name is created with lower case “employee.py”. The class is created with camel case “Employee”.

employee.py

class Employee:
	id = 1

test.py

from employee import Employee

emp = Employee();
print(emp.id);

Output

1

Table of Contents

  • ◈ Problem Formulation
  • ◈ What is TypeError in Python?
  • ◈ What Does TypeError: module object is not callable Mean?
  • ◈ Fix: TypeError: ‘module’ object is not callable
    • ✨ Method 1: Change The “import” Statement
    • ✨ Method 2: Use ModuleName.ClassName
  • Python TypeError: ‘int’ object is not callable
    • ✨ Scenario 1: Declaring a Variable Named ‘int‘
    • ✨ Scenario 2: Declaring a Variable With a Name Of Function That Computes Integer Values
  • Conclusion

Problem Formulation

Aim:

In this article we will discuss: TypeError: 'Module' Object Is Not Callable in Python and the methods to overcome such errors in your program.

Example:

Consider that you have created the following module with the name Palindrome.py :

def palindrome(val):

    return val == val[::1]

Now, you want to use this module in another program and check if an entered value is Palindrome or not :

import Palindrome

text = input(«Enter the value: «)

ans = Palindrome(text)

if ans:

    print(«Palindrome!»)

else:

    print(«Not Palindrome!»)

Let’s execute this code and check the output:

Enter the value: 21

Traceback (most recent call last):

  File «D:/PycharmProjects/pythonProject1/Reverse.py», line 4, in <module>

    ans = Palindrome(text)

TypeError: ‘module’ object is not callable

Wait!!! 😵 Why did we get this error? It brings us to a number of questions:

  • What is a TypeError?
  • What does TypeError: module object is not callable mean?
  • Why did we encounter this error in our program?
  • How to fix TypeError: module object is not callable ?

Let us dive into each question in details and find out the correct way of calling a certain module and its attributes.

TypeError is raised when a certain operation is applied to an object of an incorrect type. For example, if you try to add a string object and an integer object using the + operator, then you will encounter a TypeError because the + operation is not allowed between the two objects that are f different types.

Example:

Output:

TypeError: can only concatenate str (not «int») to str

☞ There can be numerous reasons that lead to the occurrence of TypeError. Some of these reasons are:

  • Trying to perform an unsupported operation between two types of objects.
  • Trying to call a non-callable caller.
  • Trying to iterate over a non-iterative identifier.

Now that we have a clear idea about TypeErrors, let us understand what does TypeError: module object is not callable mean?

What Does TypeError: module object is not callable Mean?

TypeError: 'module' object is not callable is generally raised when you are trying to access a module as a function within your program. This happens when you are confused between a module name and a class name/function name within that module. For example:

import socket

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

print(s)

Output:

Traceback (most recent call last):

  File «D:/PycharmProjects/pythonProject1/example.py», line 2, in <module>

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

TypeError: ‘module’ object is not callable

In the above example, we have imported the module socket; however, within the program, we are trying to use it as a function that ultimately leads to TypeError: 'module' object is not callable . The user got confused because the module name and the class name are the same.

◈ Therefore we now have an idea about the reason behind the occurrence of TypeError: 'module' object is not callable.So, why did we encounter this error in our example?

The reason is already known to us from the above explanation. If you have a look at the example, you will notice that the name of the module is Palindrome while it has a function with the name Palindrome as well. So, that’s what created the confusion!

That brings us to the all important question. How do we fix the error?

◈ Fix: TypeError: ‘module’ object is not callable

There are couple of ways you can use to fix this error.

Method 1: Change The “import” Statement

Instead of importing the module you can import the function or attribute within the module to avoid the TypeError. Let’s have a look at the solution to our example scenario in the program given below.

# import the method within the module

from Palindrome import Palindrome

text = input(«Enter the value: «)

ans = Palindrome(text)

if ans:

    print(«Palindrome!»)

else:

    print(«Not Palindrome!»)

Output:

Enter the value: refer

Palindrome!

As Python now knows that you are referring to the Palindrome function within the Palindrome Module, hence the program runs without any error.

Solution to the socket program mentioned above:

from socket import *

s = socket(AF_INET, SOCK_STREAM)

print(s)

Output:

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

Method 2: Use ModuleName.ClassName

Another workaround to our problem is to use ModuleName.ClassName or ModuleName.FunctionName instead of just using the module name which causes confusion and error.

Let’s have a look at the solution to our example scenario in the program given below.

import Palindrome

text = input(«Enter the value: «)

ans = Palindrome.Palindrome(text)

if ans:

    print(«Palindrome!»)

else:

    print(«Not Palindrome!»)

Output:

Enter the value: 121

Palindrome!

Explanation: When we use Palindrome.Palindrome(text), it tells Python that we are trying to access the Palindrome method of the Palindrome module; therefore there’s no confusion in this case and the program runs without any error.

Solution to the socket program mentioned above:

import socket

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

print(s)

Ouput:

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

Let’s have a look at another variation of this kind of TypeError in Python.

Python TypeError: ‘int’ object is not callable

You will encounter TypeError: 'int' object is not callable mostly in the following scenarios:

Scenario 1: Declaring a Variable Named ‘int

If you declare a variable with the name int and you also have a variable that accepts the user input with the help of the int() method, then the Python compiler is unable to distinguish between the inbuilt int() method and the declared variable int in the program.

Example:

int = 10

a = int(input(‘enter a value: ‘))

for i in range(1, int):

    print(i * 5)

Output:

enter a : 5

Traceback (most recent call last):

File «D:/PycharmProjects/pythonProject1/example.py», line 2, in

a=int(input(‘enter a : ‘))

TypeError: ‘int’ object is not callable

Solution: Use a different name for the variable

k = 10

a = int(input(‘enter a value: ‘))

for i in range(1, k):

    print(i * 5)

Output:

enter a value: 5

5

10

15

20

25

30

35

40

45

Scenario 2: Declaring a Variable With a Name Of Function That Computes Integer Values

Suppose you have a variable by the name sum in your program and you are also using the built-in function sum() within your program then you will come across the TypeError: 'int' object is not callable since Python won’t be able to distinguish between the two sum variable and the sum() method.

Amount = [500, 600, 700]

Discount = [100, 200, 300]

sum = 0

if sum(Amount) < 5000:

    print(sum(Amount) 1000)

else:

    sum = sum(Amount) sum(Discount)

    print(sum)

Output:

Traceback (most recent call last):

  File «D:/PycharmProjects/pythonProject1/example.py», line 4, in <module>

    if sum(Amount) < 5000:

TypeError: ‘int’ object is not callable

Solution: Use different variable instead of sum

Amount = [500, 600, 700]

Discount = [100, 200, 300]

value = 0

if sum(Amount) < 5000:

    print(sum(Amount) 1000)

else:

    value = sum(Amount) sum(Discount)

    print(value)

Output:

Conclusion

Key take-aways from this article:

  • What is TypeError in Python?
  • What Does TypeError: module object is not callable Mean?
  • Fixing the – TypeError: ‘module’ object is not callable
  • Python TypeError: ‘int’ object is not callable

Python modules are confusing, especially when you define your own. “TypeError: ‘module’ object is not callable” is one of the most common mistakes that Python developers make when working with classes.

In this guide, we talk about what this error means and why it is raised. We walk through an example code snippet to help you overcome this error. Let’s begin!

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

The Problem: TypeError: ‘module’ object is not callable

Any Python file is a module as long as it ends in the extension “.py”.

Modules are a crucial part of Python because they let you define functions, variables, and classes outside of a main program. This means you can divide your code up into multiple files and categorize it more effectively.

Modules must be imported in a certain way. Otherwise, Python returns an error:

TypeError: 'module' object is not callable

This happens when you try to import a module as a function.

An Example Scenario

Define a module called “cakes”. This module contains one function: read_file. The read_file function will read the contents of a text file.

Our filename determines the name of our module. Because we want our module to be called “cakes”, we write our code in a file called cakes.py:

def read_file():
	all_cakes = []
	with open("cakes.txt", "r") as cake_file:
		cake_list = cake_file.readlines()
		for c in cake_list:
			all_cakes.append(c.replace("n", ""))

	return all_cakes

This function reads the contents of a file called “cakes.txt”. It then iterates through every line of text in the file and adds each line to a list called “all_cakes”.

The replace() method is used to replace any new line (“n”) characters with an empty value. This removes all new lines. We return “all_cakes” at the end of our function.

Now, open a file called app.py and paste in this code:

import cakes

cake_list = cakes()
print(cake_list)

This code uses our “cakes” module to read the contents of the “cakes.txt” file. It then prints out all the cakes the function has found in the file.

Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	cakes = cakes()
TypeError: 'module' object is not callable

Our code returns an error.

The Solution

Let’s take a look at the import statement in our app.py file:

We import the module “cakes”. This contains all of the variables, classes, and functions that we declare in the “cakes.py” file.

Now, let’s look at our next line of code:

Although the “cakes” module only contains one function, we don’t specify what that function is. This confuses Python because it does not know what function it should work with.

To solve this error, we call the name of the function we want to reference instead of the module itself:

import cakes

cake_list = cakes.read_file()
print(cake_list)

Let’s try to run our code again:

['Cinnamon Babka', 'Chocolate Cupcake']

Our code successfully returns the list of cakes.

In our app.py file, we call cakes.read_file().

Python looks at the file “cakes.py” where our “cakes” module is stored and locates the read_file() function. Then, Python executes that function.

We assign the result of the read_file() function to a variable called “cake_list”. Then, we print out that list to the console.

Alternatively, import the read_file function directly into our program:

from cakes import read_file

cake_list = read_file()
print(cake_list)

Our code returns:

['Cinnamon Babka', 'Chocolate Cupcake']

Our code executes the read_file() function from the “cakes” module. In this example, we import the whole “cakes” module. Instead of doing so, we import one function from the “cakes” module: read_file.

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Notice that when we import read_file, we no longer need to use cakes.read_file() to call our function. We use read_file() because we import the read_file() function directly into our code.

Conclusion

The code for a Python module exists in a different file. There are a few different ways to import functions and values from modules and it’s easy to mess up.

When you work with modules, make sure that you reference the functions, classes, and variables that you want to access correctly. You need to specify the exact function that you want to call from a module if you want to reference a function, rather than calling the module itself.

Now you’re ready to solve this Python TypeError like a professional developer!

Понравилась статья? Поделить с друзьями:
  • Module not found error pygame
  • Module not found error pycharm
  • Module not found error no module named pip
  • Module not found error no module named numpy
  • Module library initialization error