How To Solve Error “TypeError: ‘Module’ Object Is Not Callable” In Python

typeerror: ‘module’ object is not callable in python

To fix error “TypeError: ‘module’ object is not callable” in Python, there are two solutions we have effectively tested. Follow the article to better understand.

What causes the “TypeError: ‘module’ object is not callable in Python error?

Module: A module can be thought of as a library of code or a file containing a set of functions you want to include in your application.

To create a module, you need to save the code in a file with the file extension .py

Example:

Save a piece of code in a file named ‘name.py’ is called a module.

To be able to access the module you just created, you must use the import statement.

import name

The “TypeError:’module’ object is not callable” error happens when you import as a module but call it like a function or a class, resulting in the compiler running the module name as a function.

We have two files:

1. ’name.py

def name():
	myName = 'John'
  	return myName

2. ’mycode.py

import name

print(name())

When you run ‘mycode.py‘, the program will get the following error:

Output:

Traceback (most recent call last):
  File "./mycode.py", line 3, in <module>
    print(name())
          ^^^^^^
TypeError: 'module' object is not callable

The problem here is that the compiler confuses the ‘name function’ and ‘name module’ because they are the same.

How to solve this error?

Method 1: Using the dot to access a function or a class

In the file ‘mycode.py’, I will correct it like this:

import name

print(name.name())

Output:

John

Method 2: Directly importing specific function or class

Syntax:

from module_name import function_name

Example:

1. ’name.py’ file:

def name():
    myName = 'John'
    return myName

2. ‘mycode.py’ file:

from name import name

print(name())

Output:

John

Note:

Before debugging, you should determine the module’s properties by using the dir() method.

Syntax:

dir(module_name)

Example: Find the property of  the ‘name.py’ module

import name

print(dir(name))

Output:

['__builtins__', '__cached__', '__doc__',
  '__file__', '__loader__', '__name__','__package__', '__spec__', 'do_math']

Summary

In this tutorial, I’ve explained how to solve the problem “TypeError: ‘Module’ Object Is Not Callable” in Python. If you have any questions about this issue, please comment below. I will answer your questions. Thanks for reading!

Maybe you are interested:

Leave a Reply

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