Organize Python Imports on save in VS Code

The “PEP 8 – Style Guide for Python Code” defines the following order for Python imports:

Imports should be grouped in the following order:

  • Standard library imports.
  • Related third party imports.
  • Local application/library specific imports.

You should put a blank line between each group of imports.

Taking care of that manually is just tedious work! This is something the editor or IDE should take care of instead. VS Code has a feature called Organize Imports to do exactly that, but unfortunately by default we have to run it manually. Instead, it would be much nicer if it was triggered each time we save a file. We can achieve that by adding the following to VS Codes settings.json:

{
  ...
  "editor.codeActionsOnSave": {
    "source.organizeImports": true
  }
  ...
}

And just like that we get sorted and grouped imports each time we save a file.


Posted

in

by

Tags: