In this article, we will fix the TypError that ‘module’ object is not callable in Python.
A Module is a collection of code libraries in a categorical manner.
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 the name math(), the compiler will be confused. It will throw an error called TypeError ‘module’ object is not callable in Python.
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 the 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.
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.
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 are 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 due to 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 the “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().