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() 
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.

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.