I am trying to structure my python 2.7 project (which entails several subdirectories) correctly. I have added __init__.py files on every level, and in the case of imports it seems that the "best" practice is to use absolute imports of the sort:
import top_package_folder.package_subfolder.module_name
instead of:
import .module_name
even when my code lives in the package_subfolder directory.
As I learned about this recently, I am now looking for a way to automatically convert all those relative imports to absolute ones.
(I tried autopep8 and could not manage to make imports absolute.)
Thanks in advance.
You can use absolufy-imports
https://github.com/MarcoGorelli/absolufy-imports :
pip install absolufy-imports
See pre-commit for instructions
Sample .pre-commit-config.yaml
:
- repo: https://github.com/MarcoGorelli/absolufy-imports
rev: v0.3.1
hooks:
- id: absolufy-imports
$ cat mypackage/myfile.py
from . import __version__
$ absolufy-imports mypackage/myfile.py
$ cat mypackage/myfile.py
from mypackage import __version__
Disclaimer: I'm the author of this little package
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With