A tool to automatically replace relative imports with absolute ones.
Project description
absolufy-imports
A tool and pre-commit hook to automatically convert relative imports to absolute.
Installation
$ pip install absolufy-imports
Usage as a pre-commit hook (recommended)
See pre-commit for instructions
Sample .pre-commit-config.yaml
:
- repo: https://github.com/MarcoGorelli/absolufy-imports
rev: v0.3.0
hooks:
- id: absolufy-imports
Command-line example
$ cat mypackage/myfile.py
from . import __version__
$ absolufy-imports mypackage/myfile.py
$ cat mypackage/myfile.py
from mypackage import __version__
Configuration
Application directories
If your package follows the popular ./src
layout, you can pass your application directories via --application-directories
, e.g.
$ cat src/mypackage/myfile.py
from . import __version__
$ absolufy-imports src/mypackage/myfile.py --application-directories src
$ cat src/mypackage/myfile.py
from mypackage import __version__
Multiple application directories should be comma-separated, e.g. --application-directories .:src
. This is the same as in reorder-python-imports.
Only use relative imports
Use the --never
flag, e.g.
$ cat mypackage/myfile.py
from mypackage import __version__
$ absolufy-imports mypackage/myfile.py --never
$ cat mypackage/myfile.py
from . import __version__
Keep submodules relative
Use the --keep-submodules-relative
flag. By default, submodules are considered to be the first level of the directory. E.g. if you have
├── mypackage
│ ├── library1
│ │ ├── foo.py
│ │ └── subdirectory
│ │ ├── bar.py
│ │ └── baz.py
│ └── library2
│ └── qux.py
and
$ cat mypackage/library1/subdirectory/bar.py
from mypackage.library1.subdirectory import baz
from mypackage.library1 import foo
from mypackage.library2 import qux
then you will get
$ absolufy-imports mypackage/library1/subdirectory/bar.py --keep-submodules-relative
$ cat mypackage/library1/subdirectory/bar.py
from . import baz
from .. import foo
from mypackage.library2 import qux
To specify a custom list of submodules, you can use the --submodules
flag, e.g.
$ absolufy-imports mypackage/library1/subdirectory/bar.py \
--keep-submodules-relative \
--submodules '{".": ["mypackage.library1", "mypackage.library2"]}'
Note that they need to be in json format, and the keys should be the application directories.
See also
Check out pyupgrade, which I learned a lot from when writing this.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for absolufy_imports-0.3.0-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d0ace1e4dc9d3eb3c0c8d1fd4328399ce08c891d3e2e88f6a7a99757d1c1629e |
|
MD5 | b32b06bbcd7106aef99ec83a2d5941fd |
|
BLAKE2b-256 | 0af890cdcce29e40640bf1aa302aaee58891867a6d27befbdf87eb64f4c0c494 |