Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Cannot Import from the src/ Directory

I have a project with this structure:

root-project/
    src/
        utils/
            file_check.py
        main.py
        type_aliases.py
    ...

In the src/utils/file_check.py I import something from src/type_aliases.py but I always get a ModuleNotFound exception. These are what I have tried:

from src.type_aliases import ...

I also removed the src.:

from type_aliases import ...

These are the exceptions:

ModuleNotFoundError: No module named 'src'

The second one:

ModuleNotFoundError: No module named 'type_aliases'

I ran the files through the root-project/ directory, however, I also switched to the src/ directory but I still got the exception.

I also checked the sys.path variable and added src/ directory but I still get the error:

import sys

sys.path.append("/home/eastern-skill7173/dev/python/root-project/src/")

from src.type_aliases import ...

Still the error is visible

like image 932
Omid Ketabollahi Avatar asked Feb 28 '26 04:02

Omid Ketabollahi


1 Answers

When you add the src directory to sys.path, this directory will be searched for modules during import. Hence, you can import modules directly by their name:

import sys

sys.path.append("/path/to/src")

import type_aliases
like image 154
a_guest Avatar answered Mar 04 '26 15:03

a_guest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!