在python中将所有相对导入自动转换为绝对值 [英] Convert all relative imports to absolute automatically in python

查看:40
本文介绍了在python中将所有相对导入自动转换为绝对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试正确构建我的 python 2.7 项目(包含多个子目录).我在每个级别上都添加了 __ init __.py 文件,对于导入,似乎最佳"做法是使用绝对导入的种类:

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

代替:

import .module_name

即使我的代码位于package_subfolder目录中.

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.

(我尝试使用autopep8,但无法使导入绝对化.)

谢谢.

推荐答案

您可以使用 absolufy-imports https://github.com/MarcoGorelli/absolufy-imports :

pip install absolufy-imports

用作预提交钩子

有关说明,请参见预提交

示例 .pre-commit-config.yaml :

-   repo: https://github.com/MarcoGorelli/absolufy-imports
    rev: v0.3.0
    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

这篇关于在python中将所有相对导入自动转换为绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆