简体   繁体   English

Pycharm 汽车相对进口

[英]Pycharm auto relative imports

Whenever you use autoimport provided by PyCharm it generates an absolute path import.每当您使用 PyCharm 提供的自动导入时,它都会生成绝对路径导入。 ie

from my_package.my_subpackage import my_thing

instead of而不是

from .my_subpackage import my_thing

Is there a setting to use relative imports instead of absolute ones when importing a python package?导入 python 包时是否有使用相对导入而不是绝对导入的设置?

It appears currently there is no way to change the import style for auto-import feature to use relative imports.目前似乎无法将自动导入功能的导入样式更改为使用相对导入。 The only style changes you can make to import statements are how the absolute imports are structured:您可以对 import 语句进行的唯一样式更改是绝对导入的结构方式:

在此处输入图片说明

(The Jetbrains/PyCharm settings search functionality is excellent by the way). (顺便说一下,Jetbrains/PyCharm 设置搜索功能非常好)。

The same thing happens when refactoring, it's definitely an option I'd like to see added.重构时也会发生同样的事情,这绝对是我希望添加的一个选项。

It will be possible starting with 2019.3 https://youtrack.jetbrains.com/issue/PY-6054 Note, that it will not do the relative import automatically if there are no other relative imports in that file yet.从 2019.3 开始可以使用https://youtrack.jetbrains.com/issue/PY-6054请注意,如果该文件中还没有其他相对导入,它将不会自动执行相对导入。 There is also an action to convert the existing absolute import to relative:还有一个动作可以将现有的绝对导入转换为相对导入: 在此处输入图片说明

I would advise against relative in general, you can refer to this question: https://softwareengineering.stackexchange.com/a/159505我一般建议不要相对,你可以参考这个问题: https : //softwareengineering.stackexchange.com/a/159505

Also, you can check official pep8 specs https://www.python.org/dev/peps/pep-0008/此外,您可以查看官方 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):建议使用绝对导入,因为如果导入系统配置不正确(例如当包内的目录最终位于 sys.path 上时),它们通常更具可读性并且往往表现更好(或至少给出更好的错误消息):

From my personal experience it turns out that they sometimes poorly integrate with Pycharm IDE when there's more complex package layout breaking test running through Pycharm.根据我的个人经验,当有更复杂的包布局破坏测试通过 Pycharm 运行时,它们有时与 Pycharm IDE 的集成很差。 I suppose there might be some issues in other tools too.我想其他工具也可能存在一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM