Black: The Uncompromising Code Formatter
Black is an uncompromising Python code formatter that reformats code to improve readability. It is currently at version 26.3.1 and follows a regular release cadence, with new versions typically released every few months.
Warnings
- breaking Black no longer supports running with Python 3.9 due to compatibility issues.
- gotcha Ensure that the 'tomli' package is installed, as it is required for parsing TOML configuration files.
Install
-
pip install black
Imports
- black
import black
Quickstart
import os
import black
# Format a Python file
file_path = os.environ.get('FILE_PATH', 'example.py')
with open(file_path, 'r') as f:
source_code = f.read()
formatted_code = black.format_file_contents(source_code, fast=False)
with open(file_path, 'w') as f:
f.write(formatted_code)
# Format a Python string
code = 'def foo():\n return 42'
formatted_code = black.format_str(code, mode=black.FileMode())
print(formatted_code)