Home >Backend Development >Python Tutorial >How to Avoid `sys.path` Hacks When Importing from Sibling Packages?

How to Avoid `sys.path` Hacks When Importing from Sibling Packages?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 12:10:13200browse

How to Avoid `sys.path` Hacks When Importing from Sibling Packages?

Addressing Sibling Package Imports


Importing modules from sibling packages can often pose challenges when running scripts from the command line. To alleviate these difficulties, we present an alternative solution that eliminates the need for clumsy sys.path.insert hacks.


The Approach


We will package our code into a single folder and structure it as follows:


<br>└── myproject</p>
<pre class="brush:php;toolbar:false">├── api
│   ├── api_key.py
│   ├── api.py
│   └── __init__.py
├── examples
│   ├── example_one.py
│   ├── example_two.py
│   └── __init__.py
├── LICENCE.md
├── README.md
└── tests
    ├── __init__.py
    └── test_one.py


Additionally, we will create a pyproject.toml file in the root folder to describe the package.


Installing the Package


To make our package available for imports, we will install it in an editable state using pip:


pip install -e .

Handling Imports


When importing modules from our package, we will prefix the import with myproject., as demonstrated in test_one.py:


from myproject.api.api import function_from_api

Note that this prefix is necessary only for imports that wouldn't work without the pyproject.toml file and pip install.


Running the Script


With all the necessary setup in place, we can run our script from the command line:


python .myprojectteststest_one.py

This should output the expected result:


I am the return value from api.api!

Conclusion


By incorporating these steps, we have effectively resolved the issue of sibling package imports and can now run scripts from the command line without resorting to sys.path hacks.

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