Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Jordan Bauer
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()
.
Here is an example of how the error occurs. Imagine we have 2 files -
another.py
and main.py
.
def do_math(a, b): return a + b
And here is the content for 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.
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.
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.
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.
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.
import another print(another.do_math(50, 50)) # 👉️ 100
Alternatively, you can import the do_math
function directly.
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.