简体   繁体   中英

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.

I have a PyCharm project where most of my imports are relative, like this:

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?

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. When you rename your package again the desired result will be achieved. Be careful though, this might break some other parts of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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