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)?
Answers:
PyCharm sorts imports only according to groups specified in PEP-8, not alphabetically.
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.
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.
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.
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.
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)?
PyCharm sorts imports only according to groups specified in PEP-8, not alphabetically.
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.
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.
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.
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.