1

I have package in following structure

Main_file 
 __init__.py
 main.py
 sub_folder
 __init.py
 a.py
 b.py

b.py contain

def print_value():
 print("hello")

a.py contain

import b
b.print_value()

in main.py

from sub_folder import a

when i run main.py i got following error

No module named 'b'

2 Answers 2

1

Since sub_folder is not in your PYTHONPATH, you need to use a relative import from a.py:

from . import b
b.print_value()
answered Oct 13, 2018 at 9:42
Sign up to request clarification or add additional context in comments.

Comments

0

You can also include the sub_folder into the system path by

import sys
sys.path.append(<path to sub_folder>)

Note: as observed in the comments below, this can create issues due to double loads. This works for scripts, and is not the right method to use when writing packages.

answered Oct 13, 2018 at 9:54

2 Comments

The result of that would be having two versions of each module: there would be module a and module sub_folder.a, with same contents, but treated by Python as two separate modules. Sometimes it does not matter, when you encounter bugs caused by this, they will be rather ugly bugs ;)
Thanks for the pointer! I was thinking from the point of view of writing a script, rather than a package!

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.