1

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
1
  • 1
    from .b.bb imort hello_bb (a dot before the b) Commented Sep 8, 2017 at 21:03

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I don't have to use relative import in root.py. Any ideas why it works there?
@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.
0

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")
answered Sep 8, 2017 at 21:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.