santosh adhikari
santosh adhikari

Reputation: 13

Importing module from python package

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'

Upvotes: 1

Views: 44

Answers (2)

Arjun Venkatraman
Arjun Venkatraman

Reputation: 239

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.

Upvotes: 0

pietrodn
pietrodn

Reputation: 569

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

from . import b
b.print_value()

Upvotes: 1

Related Questions