How to configure Pycharm to use a Black install within a virtual environment

TL;DR

If you are using Pycharm with Pyenv (and possibly virtual environments more generally), you need to include the $PyInterpreterDirectory$ variable in the Black program path, so that Pycharm can find it within your selected virtual environment.

So the full program path to use would be $PyInterpreterDirectory$/black (if you are on Windows, use backslash).

Screenshot of Pycharm File Watcher config window showing configuration for Black formatter.
Screenshot of Pycharm File Watcher config window

Detail

I got a bit stuck following the standard Editor Integration instructions in the Black documentation: https://black.readthedocs.io/en/latest/editor_integration.html

The instructions advise you to use the which black command to find the path to your Black installation, and then use that path as the program path in Pycharm.

If you do that when using Pyenv (and potentially other virtual env setups), you get an error similar to this when trying to run Black:

The Black documentation is aimed at people who have a global installation of Black with a consistent program path across different projects.

Using the $PyInterpreterDirectory$ variable in the program path will ensure that Pycharm always tries to run the version of Black within the same virtual environment that you are using for running your project.