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.
Consider the following file structure:
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()
To run test_one.py, ensure myproject is installed in an editable state. Then, execute:
python myproject/tests/test_one.py
You should see the output: "I am the return value from api.api!".
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!