I'm working on a Python project with the following structure:
/
├── src/
│ ├── __init__.py
│ ├── afrr/
│ │ ├── __init__.py
│ │ ├── dumper.py
│ │ └── cleaner.py
│ ├── config.py
│ ├── tests/
│ │ ├── afrr/
│ │ │ ├── __init__.py
│ │ │ └── test_afrr_dumper.py
The test_afrr_dumper.py file is intended to test the dump_afrr_data function in afrr/dumper.py. The relevant code snippets are as follows:
src/afrr/dumper.py
import os
import pandas as pd
from datetime import datetime
from src.config import PROCESSED_DIR # Ensure PROCESSED_DIR is defined in src/config.py
src/tests/afrr/test_afrr_dumper.py
from afrr.dumper import dump_afrr_data
from src.config import PROCESSED_DIR
When I attempt to run the test using either pytest or directly with Python, I encounter the following error:
ModuleNotFoundError: No module named 'src'
Setting PYTHONPATH:
set PYTHONPATH=srcVerified with
echo %PYTHONPATH%, but the error persists when running the test:pytest src/tests/afrr/test_afrr_dumper.pyAdding
__init__.py:- Added
__init__.pyfiles in the following directories to ensure they are treated as packages:src/ src/afrr/ src/tests/afrr/
- Added
Installing the Project as a Package:
- Created a
setup.pyfile:from setuptools import setup, find_packages setup( name="p", version="0.1", packages=find_packages(where="src"), package_dir={"": "src"}, install_requires=[ "pandas>=1.0.0", ], ) - Installed the project using:
pip install -e .
- Created a
Moving Test Files:
- Moved
test_afrr_dumper.pytosrc/and ran:
Still encountered the samepytest src/test_afrr_dumper.pyModuleNotFoundError.
- Moved
Expected Behavior
The src directory should be recognized as the root package, and the imports in test_afrr_dumper.py should resolve without issues. For example, from src.config import PROCESSED_DIR should work seamlessly.
Actual Behavior
Despite trying all of the above, Python consistently fails to recognize src as a module and raises `ModuleNotFoundError: No module named 'src'.
Environment Details
- OS: Windows 10
- Python Version: 3.12.8
- Virtual Environment:
venvcreated withpython -m venv - Installed Dependencies:
pandaspytest- Other standard libraries.
Questions
- How can I properly configure my project so that
srcis treated as the root module for imports? - What am I missing in terms of Python package/module resolution?
- Is there a more structural, permanent fix for this issue without relying on setting
PYTHONPATHmanually?
hyperMVPis the intended name of your package,hyperMVPshould be undersrc, and imports should befrom hyperMVP..., and then you'd need to make your package installable with a suitable pyproject.toml, and install it as editable.sys.pathandPYTHONPATH...