Zev Averbach
Posted on June 11, 2021
tl;dr install this plugin and have PyCharm start blackd
via a shell script on launch. Reassign the "reformat code" keyboard shortcut to call the plugin.
Immediate Performance Issues
Whilst making my yearly pilgrimage from vim to PyCharm (I usually go back to vim after a bit), I found it less than straightforward to apply the black formatter instead of using PyCharm's built-in "reformat code" settings.
For those who don't know what black is, it's a way to never think about formatting in Python ever again.
After following the Black docs about setting black up in PyCharm, I found the file watcher for it to be incredibly slow, interrupting the flow of my work while I waited for it to format a single file.
So I instead turned off the file watcher and remapped the "reformat code" keyboard shortcut to instead call black
on the currently displayed file. This is great, but it also opens a terminal and displays the executed command as well as
Process finished with exit code 0
every single time the code is reformatted. A little research yielded a --quiet
parameter to black
, but for whatever reason this didn't silence the output, at least not when executed via PyCharm.
Plugin?
Jetbrains IDEs have a pretty decent plugin marketplace and community. Maybe not on par with VSCode by now, but then again there's a lot more (nice) batteries included in Jetbrains IDEs than VSCode.
A quick search yielded BlackConnect, which glues PyCharm to a blackd
daemon. It requires installing and running blackd
(pip install black[d]
), but it's nice and fast and doesn't bring attention to itself. I remapped the "reformat code" keyboard shortcut to invoke BlackConnect.
A Little Bit of Configuration
Making it work on startup requires an extra step, though: I made an on_pycharm_startup.sh
file containing a single command blackd
, did chmod +x
on it, then added it to Tools>Startup Tasks. Boom! Black works quickly and silently when manually called via keyboard shortcut.
A note: BlackConnect has a "reformat on save" option, but it's just as slow as and less reliable than running black
from a file watcher. Maybe this will change at some point.
Posted on June 11, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.