‘module’ object is not callable – Python Error

Total
0
Shares

Python throws the error, ‘module’ object is not callable, when there is conflict with file name and function name and we try to use filename for calling.

This is a common error since its a practice to use file name same as class name.

Suppose you have a file SuperHero.py and you defined a function SuperHero() in it –

def SuperHero(realName = ''):
    if realName == 'Steve Rogers':
        return "Captain America"
    elif realName == 'Tony Stark':
        return "Ironman"
    elif realName == 'Bruce Banner':
        return "Hulk"
    elif realName == 'Clint':
        return "Hawkeye"
    elif realName == 'Natasha':
        return "Black Widow"
    else:
        return "Not in record"

Now you import this file into another file, GetSuperHero.py

import SuperHero
print(SuperHero('Natasha'))

This will throw error, module object is not callable.

But why this happened? Because our function name as well as filename is same, i.e. SuperHero. Now Python has imported the file or, you can say module. Modules are not callable; functions are. To correctly implement this code, we need to make few changes –

import SuperHero
print(SuperHero.SuperHero('Natasha'))

SuperHero.SuperHero tells the python that we want to access SuperHero() function from SuperHero module.

You can also do the same thing with this approach –

from SuperHero import SuperHero
print(SuperHero('Natasha'))

    Tweet this to help others

Note: Try to avoid using built-in function names. Here is the list –

abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

Convert list to string in Python

Table of Contents Hide Joining with delimiterJoining integer itemsUsing map() functionUsing lambda functionUsing LoopsLive DemoRelated Posts: Python provides join() function which could be used to convert list to string. If…
View Post

How to rename columns in Pandas Python?

Table of Contents Hide 1. Assigning new columns to attribute .columns2. Making columns copy, change required one and reassign3. Using rename() function4. Using set_axis() function5. Using lambda functionLive DemoRelated Posts:…
View Post