简体   繁体   English

如何在 PyCharm 中将所有相对导入转换为绝对导入?

[英]How do you convert all relative imports to absolute ones in PyCharm?

This is the most similar question I could find, and it's 5 years old with no answer. 是我能找到的最相似的问题,它已经 5 年了,没有答案。

I have a PyCharm project where most of my imports are relative, like this:我有一个 PyCharm 项目,其中我的大部分导入都是相对的,如下所示:

from .. import something

However, new ones automatically added are absolute:但是,自动添加的新内容是绝对的:

from project.other_package import something

Since I find absolute imports clearer, I wouldn't mind converting all the relative imports to absolute ones, but there seems to be no way to do so.由于我发现绝对进口更清晰,我不介意将所有相对进口转换为绝对进口,但似乎没有办法这样做。

Is it possible to automatically convert all relative imports in a PyCharm project into absolute ones?是否可以将 PyCharm 项目中的所有相对导入自动转换为绝对导入?

Right click into the line where the relative import is located, then click to "Show context actions".右键单击相关导入所在的行,然后单击“显示上下文操作”。 You will see the option to convert relative import to absolute one.您将看到将相对导入转换为绝对导入的选项。 Unfortunately you have to do this one by one.不幸的是,您必须一项一项地执行此操作。

Another solution would be renaming your package name (using refactor) then returning back to original package name.另一种解决方案是重命名您的包名称(使用重构),然后返回到原始包名称。 PyCharm cannot work out relative imports when you change top level package name so it converts all imports to absolute.当您更改顶级包名称时,PyCharm 无法计算相对导入,因此它将所有导入转换为绝对导入。 When you rename your package again the desired result will be achieved.当您再次重命名您的包时,将获得所需的结果。 Be careful though, this might break some other parts of the code.不过要小心,这可能会破坏代码的其他部分。

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

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