Black: The Uncompromising Code Formatter

26.3.1 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

This script demonstrates how to use Black to format a Python file and a Python code string.

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)

view raw JSON →