关于python:Pycharm自动相对导入

Pycharm auto relative imports

无论何时使用PyCharm提供的自动导入,它都会生成绝对路径导入。即

1
from my_package.my_subpackage import my_thing

而不是

1
from .my_subpackage import my_thing

是否有设置在导入python包时使用相对导入而不是绝对导入?


当前似乎无法更改自动导入功能的导入样式以使用相对导入。您可以对导入语句进行的唯一样式更改是绝对导入的结构:

enter image description here

(顺便说一句,Jetbrains / PyCharm设置搜索功能非常出色)。

重构时也会发生同样的事情,这绝对是我希望添加的选项。


有可能从2019.3开始https://youtrack.jetbrains.com/issue/PY-6054
请注意,如果该文件中还没有其他相对导入,它将不会自动进行相对导入。还有一个将现有绝对导入转换为相对导入的操作:
enter image description here


我一般建议不要亲戚,您可以参考以下问题:
https://softwareengineering.stackexchange.com/a/159505

此外,您可以查看官方的pep8规格https://www.python.org/dev/peps/pep-0008/

Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path):

根据我的个人经验,发现在Pycharm中进行更复杂的封装布局破坏测试时,有时它们与Pycharm IDE的集成度很差。我想其他工具也可能存在一些问题。