Home >Backend Development >Python Tutorial >How Can I Avoid `sys.path` Hacks When Importing Sibling Packages in Python?

How Can I Avoid `sys.path` Hacks When Importing Sibling Packages in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 13:56:10136browse

How Can I Avoid `sys.path` Hacks When Importing Sibling Packages in Python?

Sibling Package Imports: A Painless Approach

When dealing with Python imports, encountering sibling package import issues can be frustrating. Let's explore an alternative to the dreaded sys.path.insert hack to resolve this issue.

Project Setup

Consider the following project structure:

├── LICENSE.md
├── README.md
├── api
│   ├── __init__.py
│   ├── api.py
│   └── api_key.py
├── examples
│   ├── __init__.py
│   ├── example_one.py
│   └── example_two.py
└── tests
│   ├── __init__.py
│   └── test_one.py

The Problem

When you attempt to import from the api module within the examples and tests directories, you may encounter an error like:

ModuleNotFoundError: No module named 'api'

The Solution

Instead of resorting to sys.path hacks, here's a Pythonic solution:

Step 1: Create a pyproject.toml File

[project]
name = "myproject"
version = "0.1.0"
description = "My small project"

[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"

Step 2: Install with pip -e

Activate your virtual environment if needed, then install your project in editable state:

pip install -e .

Step 3: Adjust Imports

Modify the imports in files that were previously unable to import from the api module to include the project name, e.g.:

from myproject.api.api import function_from_api

Example

api.py

def function_from_api():
    return 'I am the return value from api.api!'

test_one.py

from myproject.api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

Running the Test

Ensure that you are still within your virtual environment and execute the following:

python .\myproject\tests\test_one.py

Output:

I am the return value from api.api!

The above is the detailed content of How Can I Avoid `sys.path` Hacks When Importing Sibling Packages in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn