When working with Python packages, importing modules from sibling packages can sometimes be a challenge. Traditional methods involving sys.path manipulation can be cumbersome and error-prone. Here's a solution that leverages Python's modern packaging tools for a more straightforward approach.
At the root of your project 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"]
While not essential, activating a virtual environment can ensure that your project-specific dependencies are isolated from the global Python environment. To create and activate a virtual environment:
Create the virtual environment:
python -m venv venv
In the root of your project directory, install your package using pip with the -e flag to enable editable mode:
pip install -e .
To import modules from sibling packages, add the package name as a prefix in your imports. For example, to import a module named api from a sibling package, you would use:
from myproject.api import api_module
Consider the following project structure:
- api - api.py - examples - example_one.py - tests - test_one.py
With the proposed solution, you can import the api module from example_one.py and test_one.py as follows:
example_one.py:
from myproject.api import api_module
test_one.py:
from myproject.api import api_module def test_function(): print(api_module.function_from_api()) if __name__ == '__main__': test_function()
Running test_one.py will now successfully call the function_from_api() function in the api module.
The above is the detailed content of How Can I Easily Import Modules from Sibling Packages in Python?. For more information, please follow other related articles on the PHP Chinese website!