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()

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles