Solve - TypeError: 'module' object is not callable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Jordan Bauer

Solve - TypeError: 'module' object is not callable in Python #

The Python "TypeError: 'module' object is not callable" occurs when we import a module as import some_module but try to call it as a function or class. To solve the error, use dot notation to access the specific function or class before calling it, e.g. module.my_func().

typeerror module object is not callable

Here is an example of how the error occurs. Imagine we have 2 files - another.py and main.py.

another.py
def do_math(a, b): return a + b

And here is the content for main.py.

main.py
import another # ⛔️ TypeError: 'module' object is not callable another(100, 100)

The issue is that, in the main.py file, we import the another module but call the module as if it were the do_math() function.

One way to solve the error is to use dot notation to access the specific function or class before you call it.
main.py
import another print(another.do_math(100, 100)) # 👉️ 200

We used dot notation to get access to the do_math function from another.py before calling it.

Alternatively, you can import the specific function or class directly.

main.py
from another import do_math print(do_math(100, 100)) # 👉️ 200

This import statement only imports the do_math function from the another.py module.

If you need to import multiple variables or functions, separate them by commas in the import statement, e.g. from another import first, second, third.

A good way to start debugging is to print(dir(your_module)) and see what attributes the imported module has.

Here is what printing the attributes of the another.py module looks like.

main.py
import another # 👇️ ['__builtins__', '__cached__', '__doc__', # '__file__', '__loader__', '__name__', # '__package__', '__spec__', 'do_math'] # 👈️ notice 'do_math' print(dir(another))

If you pass a module object to the dir() function, it returns a list of names of the module's attributes.

Notice the do_math attribute at the end of the list.

This means that we have to access the attribute as another.do_math to get a reference to the function.

main.py
import another print(another.do_math(50, 50)) # 👉️ 100

Alternatively, you can import the do_math function directly.

main.py
from another import do_math print(do_math(50, 50)) # 👉️ 100

The "TypeError: 'module' object is not callable" means that we are trying to call a module object instead of a function or a class.

To solve the error, we have to access an attribute on the module object that points to the specific function or class.

Use the search field on my Home Page to filter through my more than 1,000 articles.