tl;dr;
isort (PyPI; GitHub) is a wonderful tool that will sort imports in Python automagically, so that you no longer have to either a) ignore eye-sores during code reviews, or b) sound like an angry grandparent asking people to sort/organize imports.
Quick Setup
If you know your away around the *nix environment, these are the abridged instructions:
- Make the
isort
binary available somewhere in your path. - Install the
isort
plugin for the editor of your choice. - Profit
NOTE: (Optional but recommended) Add a .isort.cfg
file to your HOME directory, so that even you are working on a random script or project that doesn’t have one, the powers of isort
are still available to you.
Drudgerous Line-by-Line Instructions (or my setup)
- If you don’t have one already, create a new system-wide Python virtualenv.
- The way I’d do that is to do:
/path/to/bin/python/virtualenv ~/.venv
- The way I’d do that is to do:
- Install isort.
~/.venv/bin/pip install isort
- (Generic command:
/path/to/venv/pip install isort
)
- Add the
bin
directory of your system-widevirtualenv
to your path, or just the select binaries that you want.- I have already added
~/bin/
to my path via bash-ftw, so my preference is to just symlink the specific binaries that I need. - For convenience, I’ve symlinked the following:
ln -s ~/.venv/bin/isort ~/bin/isort
ln -s ~/.venv/bin/python3 ~/bin/python3
ln -s ~/.venv/bin/pip ~/bin/pip
- I have already added
- Install an isort plugin for your editor (in my case,
emacs
, The best text editor in the world™).- For
emacs
only:- For EZMODE™, my dotemacs setup is on GitHub (just
git clone
,make install
, and you’re set!) - Add two lines to your dotemacs (typically
~/.emacs.el
or~/.emacs.elc
, or somewhere in your Emacs load path):(require 'py-isort)
(add-hook 'before-save-hook 'py-isort-before-save)
- For EZMODE™, my dotemacs setup is on GitHub (just
- No longer have to manually organize your Python imports anymore! The
isort
plugin will do it for you automatically whenever you save your file.
- For
Thank You!
Thanks for reading; now go forth and write some awesome Python code!
Questions, comments, suggestions? Leave a comment or subscribe to the blog for future helpful tips!