Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Automatically Sort Your Python Imports in Flask and Django with isort

automatically-sort-your-python-imports-in-flask-and-django-with-isort.jpg

No longer worry about alphabetizing or spacing out imports that are from the standard lib, a third party library or your own code.

Quick Jump:

You can pip3 install isort and then run the command below to sort all of your imports:

isort .

You can also run it in check mode which is handy for running it in CI so that CI will fail if your imports aren’t sorted:

isort . --check

You can also create a pyproject.toml file to configure it, such as:

[tool.isort]
profile = "black"
force_single_line = true

I like using Black and this will ensure isort formats everything in a Black compatible way.

If you use a custom line length with Black you can configure that too:

[tool.black]
line-length = 79

[tool.isort]
profile = "black"
line_length = 79
force_single_line = true

The above is a config that’s compatible with flake8, Black and isort.

The last option will convert:

from third_party import (
    lib1,
    lib2,
    lib3,
    lib4,
)

Into this:

from third_party import lib1
from third_party import lib2
from third_party import lib3
from third_party import lib4

I prefer this style but there’s many other ways documented in their multi-line output modes page as well as having other config options available in their docs.

I’m now using this tool in my example Flask and Django Docker web app projects.

# Demo Video

Timestamps

  • 0:14 – Python import sorting style best practices
  • 1:02 – Running isort to see the before and after
  • 2:25 – It is compatible with Black
  • 2:29 – Customizing styles for when your imports need more than 1 line
  • 4:48 – I’ve added shortcuts to run it in my example apps
  • 5:01 – Check mode will check your files and exit 1 if they’re not sorted
  • 6:41 – Which isort options do you use?

References

Are you using isort, if so what options do you use? Let me know below!

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments