Home > Enterprise >  How to import a module into another module
How to import a module into another module

Time:05-11

This is the structure of my project:

project (folder)
   main.py
   assets (folder)
      a.py
      b.py

When I import module a into module b and run main.py, I get No module named 'a'.

Yet if I run b.py directly, it imports a.py just fine.

a and b are in the same directory, so what am I missing? FWIW, I am using Python 3.10.

main.py:

import assets.b as bb

a.py:

def func(x):
    print(x)

b.py:

import a
a.func('hello')

CodePudding user response:

Update your b.py as follows

from . import a 
a.func('hello')

or

from assets import a
a.func('hello')

In first case, we are telling interpreter to check in the same location as file. In second case, we are just using a fullpath. Tested with python 3.10.1 and 3.6

If you are using a folder structure, it is always best to fix you execution path and relative path according to your main.py. Implies running python3.10 b.py from assets is not acceptable.


In case, you want the functionality to do python3.10 b.py from assets folder and also python3.10 main.py then update the code as follows.

try:
  from . import a
except:
  import a

a.func('hello')

If you are sticking to a IDE like PyCharm then such errors are easy to spot and fix.

  • Related