module has no attribute


I have a directory with a number of .py files in it. each file defines some classes. I also have an empty in the directory.

For example:


I am trying to import mymodule and access the classes defined in all these files:

from myproject import mymodule

print mymodule.api.MyClass 

It gives me an error saying that mymodule has no attribute api. Why? And why I can access just one of the files ( and not the others?

In [2]: dir(banners)
Asked By: akonsu



Modules don’t work like that.

from myproject.mymodule import api
print api.MyClass
Answered By: Daniel Roseman

You need an in the myproject directory too. So your module structure should be:

Answered By: Akash

The problem is submodules are not automatically imported. You have to explicitly import the api module:

import myproject.mymodule.api
print myproject.mymodule.api.MyClass

If you really insist on api being available when importing myproject.mymodule you can put this in myproject/mymodule/

import myproject.mymodule.api

Then this will work as expected:

from myproject import mymodule

print mymodule.api.MyClass 
Answered By: Rob Wouters

If you are an idiot, like me, then also check whether you didn’t name your python file the same as the module you are trying to import.

Answered By: Olaf
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.