A Starter for Python 2 Code Formatting with Black
Some of the projects I participate in still use Python 2.7. It can be an effort to install Black in this case without practice, so I’d like to show a series of steps as follows to save your time.
- Running Black requires Python 3, even for formatting Python 2 code.
- The following assumes you have admin/root privileges and use pip as your package installer. Adjustments may be required to match your env.
Table of Contents
Prerequisites: Python 3.6+ with a package installer
I’m not to provide details on how to install Python 3 and ensure a package installer (e.g., pip). You might search the web if your env did not meet the prerequisites.
command -v python3
python3 -m pip -V
Install a specific Black version
python3 -m pip install 'black[python2]==21.12b0' click==8.0.4
V21.12b0 is the last Black version with support for formatting Python 2 code. As defined in this Black version’s setup.py
, click >= 7.1.2
is a must.
click <= 8.0.4
is also required. Otherwise, you may encounter an error saying ImportError: cannot import name '_unicodefun' from 'click'
when running Black.
The above python2
key of Black means to install the optional dependency typed-ast, which has been archived and no longer needed for most use cases. If there was no matched pre-built binary package for your env, you might sometimes find it problematic to build one, complaining about either a Clang or a GCC issue. My suggestion is to remove [python2]
as shown below. It generally works fine.
python3 -m pip install black==21.12b0 click==8.0.4
Verify installation
python3 -m black --version