Convert all relative imports to absolute automatically in python
Asked Answered
P

1

18

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.

Penrod answered 18/12, 2014 at 14:51 Comment(4)
Why do you think it's best to use absolute imports?Kevenkeverian
@martineau,thats a good question. I reached this conclusion after an online search, which suggested that up to a point absolute imports were "kind of mandatory" for projects run as packages, until after python 2.5 when Guido mentioned its not any more, but nevertheless implied relative imports are still useful only in particular cases (but did not elaborate any more on that).Penrod
btw, best answer on relative imports ever: https://mcmap.net/q/14223/-relative-imports-for-the-billionth-timePenrod
you'll find most python devs prefer the from top_package.sub_package import module_name style. import top_package_folder.package_subfolder.module_name makes your code fantastically verboseSurfacetosurface
A
11

You can use absolufy-imports https://github.com/MarcoGorelli/absolufy-imports :

Installation

pip install absolufy-imports

Usage as a pre-commit hook

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

Command-line example

$ 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

Adala answered 3/2, 2021 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.