Import local package from a subdirectory python

Question:

Edit 1: Some context – This is a data science project where main.py kicks off processing and analysis. It is not going to be packaged up.

Edit 2: On why the following is not an acceptable answer: Module not found running on command line
The solution is basically, "don’t do it". This is a common data science setup. It ought to work.

Edit 3: This is the ideal solution: Create a setup.py file in the root dir:

# project/setup.py

from setuptools import find_packages, setup

setup(
    name='project',
    packages=find_packages(),
    version='0.1.0',
    description='',
    author='me',
    license='',
)

In your requirements.txt add this entry: -e . and run: pip install -r requirements.txt


Original question

My project structure is as follows:

project/
|-- src/
    |-- __init__.py
    |-- main.py
    |-- my_module.py
# my_module
const = 1
# main.py
from src.my_module import const

When I run main.py as:

/project> python src/main.py

I get:

No module named 'src'

Is there a non hacky way around this problem?

Asked By: GlaceCelery

||

Answers:

Since they are in the same folder, you can import it like this from my_module import const

Answered By: Kyriakos Psarakis
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.