[Python] Adding an upstream relative path to project in pyproject.toml

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    I created a project with uv that has the following package structure: a src folder has all the modules and functions a data folder and a notebook and script folders where the modules in src and data are loaded. However, I cannot find a way to append the root path to the project and end up getting:

    ModuleNotFoundError: No module named 'src'


    To be able to load the modules in src in a jupyter notebook, I need to add to every notebook

    import sys
    sys.path.append('..')


    And to load them in a python script in the scripts folder, I need to use the approach described here (https://stackoverflow.com/a/77576864).

    import os
    import sys

    project_path = os.path.abspath(os.path.join('..','sample_template'))
    if project_path not in sys.path:
    sys.path.insert(0, project_path)


    While both options work, I was hoping to have a more general solution that would not require repeating the sys append/insert to every script.

    Project tree:

    sample_project
    ├───.pytest_cache
    ├───.ruff_cache
    ├───.venv
    ├───.vscode
    ├───data
    │ sample_data.csv
    ├───notebooks
    │ sample_notebook.ipynb
    ├───scripts
    │ sample_script.py
    │ sample_script_declared.py
    │ __init__.py
    ├───src
    │ │ __init__.py
    │ │
    │ ├───sample_template
    │ │ │ sample_functions.py
    │ │ │ __init__.py
    │ │ │
    │ │ └───__pycache__
    │ │
    │ ├───sample_template.egg-info
    │ │
    │ └───__pycache__
    │ __init__.cpython-313.pyc
    │
    └───tests
    │ conftest.py
    │ test_sample_functions.py
    │ __init__.py
    │
    └───__pycache__



    pyproject.toml:

    [project]
    name = "sample-template"
    version = "0.1.0"
    description = "Add your description here"
    readme = "README.md"
    license = {text = "MIT License"}
    requires-python = ">=3.13"
    dependencies = [
    "pandas>=2.2.3",
    ]

    [project.scripts]
    sample-template = "sample_template:main"
    sample_script_declared = "scripts:sample_script_declared"

    [build-system]
    requires = ["setuptools>=72.0"]
    build-backend = "setuptools.build_meta"

    [tool.setuptools.packages.find]
    where = ["src"]
    include = ["sample_template*"]

    [dependency-groups]
    dev = [
    "ipykernel>=6.29.5",
    "ruff>=0.9.10",
    "pytest>= 8.3.5",
    "pip>=24.2",
    ]

    Continue reading...

Compartilhe esta Página