Home >Backend Development >Python Tutorial >How to Avoid `sys.path` Hacks When Importing from Sibling Packages?
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.
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.
To make our package available for imports, we will install it in an editable state using pip:
pip install -e .
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.
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!
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!