Integrating sibling packages and executing scripts from various directories can be challenging. This guide presents a detailed solution that avoids the infamous sys.path hacks.
Consider the following directory 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
Step 1: Create a pyproject.toml File
In your root directory, create a pyproject.toml file with the following minimal contents:
[project] name = "myproject" version = "0.1.0" description = "My small project" [build-system] build-backend = "flit_core.buildapi" requires = ["flit_core >=3.2,<4"]
Step 2: Use a Virtual Environment (Recommended)
Create and activate a virtual environment for isolation and dependency management.
Step 3: Install Your Project
Install your project in editable state using pip:
pip install -e .
Step 4: Add myproject. Prefix
In imports where relative or absolute imports fail, add the myproject prefix to the import statement:
from myproject.api.api import function_from_api
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()
Navigate to the tests directory and execute test_one.py:
python .\myproject\tests\test_one.py
This solution provides a clean and portable way to import sibling packages without sys.path manipulation. By utilizing pyproject.toml and installing your project editably, you can ensure that changes to your scripts are automatically reflected in the installed package. This approach streamlines development and simplifies project management.
The above is the detailed content of How Can I Effectively Import Sibling Packages in Python Without Using `sys.path` Hacks?. For more information, please follow other related articles on the PHP Chinese website!