Python can't import module

Question:

I found a lot of similar questions, but no one gave any answer. Still doesn’t work.

My current structure:

Project: 
- exp: 
   -- main.py
- mypac: 
   - internal: 
      -- __init__.py
      -- next_mod.py
   -- __init__.py
   -- file.py

../Project/mypac/__init__.py:

from .internal.next_mod import print_smth

../Project/mypac/internal/next_mod.py:

def print_smth():
    print(f'{__name__} from another module')

../Project/exp/main.py:

from mypac import print_smth

print_smth()

I tried lot of different approaches, but nothing prevent from error:

ModuleNotFoundError: No module named 'mypac'
  1. sys.path.append('../mypac') – not working
  2. sys.path.abspath + dir + __file__ – not working
  3. VS code JSON launch PYTHONPATH config – not working

and the rest i found at SOF.

Can anyone help me to figure out what the mistake?

Asked By: calm27

||

Answers:

One easy solution is to run main.py as a module from the Project directory:

~/Project> python -m exp.main
mypac.internal.next_mod from another module

Alternatively, you can add the Project directory to the path (not the mypac directory). By using pathlib and __file__ you can even make it independent of the actual name and location of the directory.

import sys, pathlib
# Add Project/ dir to path.
sys.path.append(str(pathlib.Path(__file__).parent.parent.absolute()))

from mypac import print_smth
print_smth()
# mypac.internal.next_mod from another module
Answered By: BoppreH

You’re running main.py module as the entry point. By default Python inserts "its" directory which is .....Project/exp to the sys.path.

It knows nothing about mypac directory. In order to let him know about it, you need to manually add "its" directory to the sys.path which is the Project directory.

Add the following before your import statement: (Use absolute path instead of placeholders)

import sys
sys.path.insert(0, ".....Project/")

from mypac import print_smth

print_smth()  # mypac.internal.next_mod from another module

You could also add this directory using PYTHONPATH environment variable and run your script like:

PYTHONPATH='....Project/' python main.py
Answered By: S.B

I would not recommend using sys.path.insert... to make this code work.
Instead create a setup.py file and install your package correctly.
You can view this question as a reference point – What is setup.py?

Answered By: Barak Fatal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.