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
Release: 2024-12-11 13:56:10
Original
174 people have browsed it

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
Copy after login

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'
Copy after login

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"
Copy after login

Step 2: Install with pip -e

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

pip install -e .
Copy after login

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
Copy after login

Example

api.py

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

test_one.py

from myproject.api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()
Copy after login

Running the Test

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

python .\myproject\tests\test_one.py
Copy after login

Output:

I am the return value from api.api!
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template