Using black and isort with Vim

FYI, the easiest way to get Vim to automatically run black and isort over a Python buffer when saving is to use Ale’s fixer functionality.

" In ~/.vim/after/ftplugin/python.vim (or somewhere like that)
let b:ale_fixers = ['black', 'isort']
let b:ale_fix_on_save = 1

If you’re only using black/isort in a subset of your projects, you can enable the b:ale_fix_on_save setting conditionally:

let b:ale_fix_on_save = 0
let filepath = expand('%:p:h')
if match(filepath, 'some-project-name') != -1
    let b:ale_fix_on_save = 1
endif

Further, if you don’t want these fixers applied on save, set

let b:ale_fix_on_save = 0

and use :ALEFix to run the fixers manually.

——————

Something wrong? Suggest an improvement or add a comment (see article history)
Tagged with: vim
Filed in: tips

Previous: Avoiding package lock-out when provisioning Ubuntu 18.04 machines
Next: Beware of changing the 'related name' of a Django model field

Copyright © 2005-2023 David Winterbottom
Content licensed under CC BY-NC-SA 4.0.