Can PyCharm's optimize imports also alphabetize them?

Question:

I am enjoying PyCharm’s optimizing of Python imports – as well as removing unused imports, following PEP8 gives them a sensible layout and makes them easier to read. Is there any way to get PyCharm to additionally alphabetize them (which would make scanning them faster, for me at least)?

Asked By: lofidevops

||

Answers:

PyCharm sorts imports only according to groups specified in PEP-8, not alphabetically.

Answered By: CrazyCoder

As already mentioned it seems that Code -> Optimize imports cannot do that.

There is however a plugin named Lines sorter (exists in the PyCharm repositories) with which one can mark all import lines and chose Edit -> Sort lines. Not perfect but easier than doing it all by hand.

Answered By: Zitrax

Additional answer for the more vim-minded. You can install IdeaVim and use Shift + V, select lines to be sorted, and a call to :sort to do it.

Answered By: Chuck

PyCharm does this automatically now by use of Code -> Optimize Imports. It also sorts them into groups per PEP 8.

See https://www.jetbrains.com/help/pycharm/optimizing-imports.html for details.

Answered By: Quark

This would be a nice addition to PyCharm indeed.

Until that time there’s a command line tool that does what you want called isort. It doesn’t come with a plug-in for PyCharm, but can be integrated via an External command and the Synchronize files after execution option, as described in their docs. You could even hook it to the original key binding.

Answered By: Pieter Ennes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.