Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycharm auto relative imports

Tags:

Whenever you use autoimport provided by PyCharm it generates an absolute path import. i.e.

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?

like image 575
Laimonas Sutkus Avatar asked Feb 09 '18 09:02

Laimonas Sutkus


People also ask

How do I fix an import error in PyCharm?

Troubleshooting: Try installing/importing a package from the system terminal (outside of PyCharm) using the same interpreter/environment. In case you are using a virtualenv/conda environment as your Project Interpreter in PyCharm, it is enough to activate that environment in the system terminal and then do the test.

How do I remove unused imports in PyCharm?

please use the default key combination below. CTRL + ALT + O ---> to remove the unused imports in windows. However, you can also change the keymap of "Optimize Imports" in settings.

How do I add imports in PyCharm?

PyCharm can do both. Type the name of the package and hit Alt-Enter , then choose Install and Import package . PyCharm will do both: you'll see a notification during the installation, then the import will be generated in the right way, according to your project styles.

What does optimize imports mean in PyCharm?

PyCharm can clean all of that up using Optimize Imports , which cleans up your imports based on settings you can save. This action can be run on a single file or across all files in a project. Also, the Commit dialog box has a checkbox to run it in the Before Commit section.


2 Answers

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. There is also an action to convert the existing absolute import to relative: enter image description here

like image 20
Sergey K. Avatar answered Oct 16 '22 16:10

Sergey K.


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:

enter image description here

(The Jetbrains/PyCharm settings search functionality is excellent by the way).

The same thing happens when refactoring, it's definitely an option I'd like to see added.

like image 126
ptr Avatar answered Oct 16 '22 16:10

ptr