I have the following structure for my Python modules:
.
├── a
│ ├── __init__.py
│ ├── aa.py
│ └── b
│ ├── __init__.py
│ └── bb.py
└── root.py
Contents of aa.py
from b.bb import hello_bb
def hello_aa():
hello_bb()
print("hello from aa.py")
Contents of bb.py
def hello_bb():
print("hello from bb.py")
Contents of root.py
from a.aa import hello_aa
hello_aa()
With Python 3.5.1, executing python root.py gives the following error:
Traceback (most recent call last):
File "root.py", line 1, in <module>
from a.aa import hello_aa
File ".../a/aa.py", line 1, in <module>
from b.bb import hello_bb
ImportError: No module named 'b'
Both the __init__.py are empty.
Anything else I am missing to make this work?
asked Sep 8, 2017 at 21:00
armundle
1,1793 gold badges16 silver badges29 bronze badges
-
1from .b.bb imort hello_bb (a dot before the b)thebjorn– thebjorn2017年09月08日 21:03:37 +00:00Commented Sep 8, 2017 at 21:03
2 Answers 2
Use relative import inside a package (see PEP 328)
aa.py
from .b.bb import hello_bb
root.py
from .a.aa import hello_aa
answered Sep 8, 2017 at 21:04
FabienP
3,1581 gold badge24 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
armundle
I don't have to use relative import in
root.py. Any ideas why it works there?FabienP
@armundle, I think it is because there is no
__init__.py in the directory of root.py. BTW this directory should not be considered as a package because of this. You have module root.py and package a with submodule b.In the aa.py file you must import hello_bb like so:
from .b.bb import hello_bb
def hello_aa():
hello_bb()
print("hello from aa.py")
Comments
lang-py