Pycharm + Black with Formatting on Auto-save

Akshay Jain
3 min readJun 11, 2021

--

So, lately, I’ve been working with Black for Python code formatting. Pretty cool huh!

I’ve seen Black do wonders to my code. It made my (already pretty) code look prettier, I could just gawk at it for hours. But, running black on every file became a tedious task as the size of the project grew. This triggered an urge to find a way to run black as soon as the file is saved.

Here, I’m presenting a way to do that with Pycharm on MacOS.

Firstly, install black in your virtualenv if not already done.

$ pip install black

You can as well install the package from pycharm preferences.

  • Pycharm > Preferences
  • Search for Python Interpreter
  • Click on the “+” icon and type “Black”
  • Click on install package

Once you’ve installed Black, click Apply and OK.

You need to open the Preferences again. This time search for External tools.

  • Preference > Tools > External Tools
  • Click on the “+” icon
  • Mention your desired Name in the Name input, and give it some description.
  • In tool settings, update as following
Programs: $PyInterpreterDirectory$/black
Arguments: $FilePath$
Working directory: $ProjectFileDir$
  • Click on “OK”

Now, you’ve done the basic setup of Black and you can now format any file by going on Tools > External Tools ( Your Group name, mine is Black) > Black.

But wait, if we have to do it for every file, then how does it solve the problem, where is the functionality to run black on auto-save.

Hold your Horses…

We need to go to preferences yet again, I promise this will be the last time.

  • Preferences > Search “File Watchers”
  • Under Tools > File Watchers > Click on the “+” icon.
  • Select “custom”

In the dialog box which appears,

  • Input Name of your choosing in “Name”
  • In File type select “Python”
  • In ‘tool to run on changes’ input following
Program: $PyInterpreterDirectory$/black
Arguments: $FilePath$
Output paths to refresh: $FilePath$
Working directory: $ProjectFileDir$

Click on “OK” and you’re good to go.

Now just restart your Pycharm instance and you can witness the “Black” magic.

Cheers 🥂

--

--

Akshay Jain
Akshay Jain

Written by Akshay Jain

A good human, a programmer, a traveller and an explorer.

Responses (8)