Q: Getting a ModuleNotFoundError when trying to import from a particular module The directory I have looks like this:
repository
  /src
    /main.py
    /a.py
    /b.py
    /c.py

I run my program via python ./main.py and within main.py there's an important statement from a import some_func. I'm getting a ModuleNotFoundError: No module named 'a' every time I run the program.
I've tried running the Python shell and running the commands import b or import c and those work without any errors. There's nothing particularly special about a either, it just contains a few functions.
What's the problem and how can I fix this issue?

A: Maybe you could try using a relative import, which allows you to import modules from other directories relative to the location of the current file.
Note that you will need to add a dot (.) before the module name when using a relative import, this indicates that the module is in the same directory as the current file:
from . import a

Or try running it from a different directory and appending the /src path like this:
import sys
sys.path.append('/src')

You could also try using the PYTHONPATH (environment variable) to add a directory to the search path:

*

*Open your terminal and navigate to the directory containing the main.py file (/src).


*Set the PYTHONPATH environment variable to include the current directory, by running the following command
export PYTHONPATH=$PYTHONPATH:$(pwd)
At last you could try to use the -m flag inside your command, so that Python knows to look for the a module inside the /src directory:
python -m src.main


A: repository/
  __init__.py
  /src
  __init__.py
  main.py
  a.py
  b.py
  c.py

In the __init__.py in repository, add the following line:
from . import repository

In the __init__.py in src, add the following line:
from . import main
from . import a
from . import b
from . import c

Now from src.a import your_func is going to work on main.py

A: I've had similar problems in the past. Imports in Python depend on a lot of things like how you run your program, as a script or as a module and what is your current working directory.
Thus I've created a new import library: ultraimport It gives the programmer more control over imports and lets you do file system based, relative imports.
Your main.py could look like this:
import ultraimport
a = ultraimport('__dir__/a.py')

This will always work, no matter how you run your code, no matter what is your sys.path and also no init files are necessary.
