A tool and pre-commit hook to automatically convert relative imports to absolute.
$ 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
$ absolufy-imports mypackage/myfile.py
- from . import __version__
+ from mypackage import __version__
If your package follows the popular ./src
layout, you can pass your application directories via --application-directories
, e.g.
$ absolufy-imports src/mypackage/myfile.py --application-directories src
- from . import __version__
+ from mypackage import __version__
Multiple application directories should be colon-separated, e.g. --application-directories .:src
. This is the same as in reorder-python-imports.
Use the --never
flag, e.g.
$ absolufy-imports mypackage/myfile.py --never
- from mypackage import __version__
+ from . import __version__
Don't absolufy (backward or forward) relative imports less or equal to the specified depth.
Usage: --depth N
with N
as integer.
--never
and--depth N
are mutually exclusive
In other words, when choosing --depth 1
you can only use relative
imports for files/folders in the same package. See the following examples
Folder:
mypackage
|-- mysubpackage
| |-- __init__.py
| |-- example.py
|-- __init__.py
|-- main.py
$ absolufy-imports mypackage/mysubpackage/__init__.py --depth 1
from .example import __file__
- from ..main import __file__
+ from mypackage.main import __file__
$ absolufy-imports mypackage/mysubpackage/__init__.py --depth 0 # default value
- from .example import __file__
+ from mypackage.mysubpackage.example import __file__
- from ..main import __file__
+ from mypackage.main import __file__
With: mypackage.mysubpackage.__init__.py
content:
from .example import __file__
from ..main import __file__
$ absolufy-imports mypackage/__init__.py --depth 1
- from .mysubpackage.__init__ import __file__
+ from mypackage.mysubpackage.__init__ import __file__
from .mysubpackage import __init__ as i
With mypackage.__init__.py
content:
from .mysubpackage.__init__ import __file__
from .mysubpackage import __init__ as i