Home > Backend Development > Python Tutorial > How to Import from Sibling Packages Without Using `sys.path` Hacks?

How to Import from Sibling Packages Without Using `sys.path` Hacks?

Linda Hamilton
Release: 2024-12-08 15:56:13
Original
253 people have browsed it

How to Import from Sibling Packages Without Using `sys.path` Hacks?

Sibling Package Imports: A Solution to Avoid sys.path Hacks

Importing from sibling packages can pose a challenge when organizing your codebase. While sys.path.append hacks offer a workaround, there's a more elegant solution that eliminates the need for these intrusive insertions.

Steps:

  1. Create a pyproject.toml File:
    Define your package metadata and dependencies in a pyproject.toml file.
  2. Use a Virtual Environment:
    Isolate your project from system dependencies by creating a virtual environment.
  3. Install Your Project in Editable State:
    Use pip and the -e flag to install your package in an editable state, ensuring changes are automatically reflected.
  4. Modify Imports:
    Prepend myproject. to imports that were previously failing, e.g., from myproject.api import function_name.

Example:

Consider the following file structure:

  • api/api.py
  • examples/example_one.py
  • tests/test_one.py
  • pyproject.toml

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

To run test_one.py, ensure myproject is installed in an editable state. Then, execute:

python myproject/tests/test_one.py
Copy after login

You should see the output: "I am the return value from api.api!".

Conclusion:

This method allows you to import from sibling packages without resorting to hacky solutions like sys.path.append. By leveraging pyproject.toml and editable installs, you can maintain a clean and modular codebase while facilitating easy extensibility and testing.

The above is the detailed content of How to Import from Sibling Packages Without Using `sys.path` Hacks?. 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