I want to import and use my own package in the upper directory with Python, but I could not find a solution when I do not want to import by relative path or change sys.path in the script, so I will write it down.
In conclusion, create setup.py
and use the command pip install -e .
.
Directory configuration example:
project
+ mypackage
| + __init__.py
| + module_a.py
+ program_main
| + executor
| + executor.py
| + tests
| + executor_test.py
I want to import and use my own package called mypackage
in the upper folder from ʻexecutor.py`.
In my case, there were multiple directories for AWS Lambda services, and LambdaLayer was placed in a higher folder as a common process, so LambdaLayer could not be imported correctly locally from Lambda functions.
Also, Lambda services and Lambda Layer have a directory structure that works fine in the deployed environment, but you have to be careful about the path when unit testing with CICD.
project
+ layers
| + my_layer_1
| + ...
| + ...
+ lambda
| + service_1
| + handler.py
| + serverless.yml
| + requirements.txt
| + env
| + ...
| + tests
| + ...
| + ...
+ setup.py
You can manage packages with setup.py
. Put the following setup.py
in the root directory.
from setuptools import setup, find_packages
setup(name='myproject', version='1.0', packages=find_packages())
find_packages () will automatically find the package where __init__.py
exists. If the path doesn't work or you can't find it, you may want to play with package_dir
in addition to packages
or check if __init__.py
exists.
After that, install your own package by executing the following command in the root directory.
pip install -e .
-e reference
e, --editable <path/url>
Install a project in editable mode (i.e. setuptools “develop mode”) from a local project path or a VCS url.
If you specify -e, when you edit and save your own package, it will automatically recognize the changes, so you do not need to reinstall your own package (pip install).
https://stackoverflow.com/questions/17155804/confused-about-the-package-dir-and-packages-settings-in-setup-py
Recommended Posts