module has no attribute
Question:
I have a directory with a number of .py
files in it. each file defines some classes. I also have an empty __init__.py
in the directory.
For example:
myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py
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 (models.py
) and not the others?
In [2]: dir(banners)
Out[2]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__',
'models']
Answers:
Modules don’t work like that.
from myproject.mymodule import api
print api.MyClass
You need an __init__.py
in the myproject directory too. So your module structure should be:
myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py
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/__init__.py
:
import myproject.mymodule.api
Then this will work as expected:
from myproject import mymodule
print mymodule.api.MyClass
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.
I have a directory with a number of .py
files in it. each file defines some classes. I also have an empty __init__.py
in the directory.
For example:
myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py
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 (models.py
) and not the others?
In [2]: dir(banners)
Out[2]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__',
'models']
Modules don’t work like that.
from myproject.mymodule import api
print api.MyClass
You need an __init__.py
in the myproject directory too. So your module structure should be:
myproject
__init__.py
mymodule
__init__.py
api.py
models.py
views.py
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/__init__.py
:
import myproject.mymodule.api
Then this will work as expected:
from myproject import mymodule
print mymodule.api.MyClass
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.