Organize Python Imports on Save in VS Code

Max Rosin

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.

Max Rosin

I am a Systems Engineer from Germany. In my personal time I like to tinker with all kinds of technologies, some of it is available here at my blog. In my professional life I work a lot with Kubernetes and monitoring systems. Occasionally I give workshops about Kubernetes and conference talks about my work.
If you want to talk about one of my posts, feel free to reach out via Twitter.