isort is a Python utility / library to sort imports alphabetically, and automatically separated into sections. It’s very useful in Django projects, specially in views where we usually deal with a great amount of imports.
Organizing the imports in sections is easy, but to keep them in alphabetical order is very tedious. I don’t know about you, but sometimes I have to run all the letters in my head to make sure 😂.
Installation
Install it via pip or grab the code from GitHub:
Usage
You can already start using it without any configuration:
You can also apply the changes or check for errors recursively:
Django
This is how I like to organize my imports in a Django project:
- Future imports
- Python Standard Libraries
- Django core
- Third party libraries (related or not to Django)
- First party libraries (that is, our project’s imports)
- Local imports
You can achieve this by adding a configuration file in the project root. Either add a setup.cfg or a file named .isort.cfg in the project root.
setup.cfg
This is an example of the final result:
If you need to have imports out of order, to avoid circular import for example, you can use the isort:skip
comment:
You can find out more about the isort library visiting its GitHub Page.