TypeError: ‘module’ object is not callable

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.

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

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

0 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…