blacken-docs
blacken-docs is a command-line tool that formats Python code blocks within various documentation files (Markdown, reStructuredText, LaTeX, and Python docstrings) using the opinionated `Black` formatter. It operates by rewriting files in place. The library is currently at version 1.20.0, actively maintained, and releases occur periodically to support new Python versions and `Black` features.
Common errors
-
code block parse error Cannot parse: X:Y: <error_details>
cause This error occurs when `blacken-docs` or `Black` cannot parse the content of a code block, typically due to invalid Python syntax, an incorrect language specifier, or malformed `pycon` (interactive console) blocks in older versions.fixEnsure the code within the block is valid Python syntax. If using `pycon` blocks with `>>>` prompts, ensure your `blacken-docs` version is 1.9.0 or newer, which added explicit support for these. -
pre-commit hook 'blacken-docs' fails and reformats files, then subsequent local `black` runs or CI checks fail, creating a formatting loop.
cause This 'formatting loop' usually indicates that different versions of `Black` are being used by your local environment, `pre-commit` hook, and/or CI system, leading to conflicting formatting styles.fixStandardize the `Black` version across all environments. For `pre-commit`, explicitly pin `Black` in `additional_dependencies` of the `blacken-docs` hook (e.g., `additional_dependencies: ['black==24.4.0']`). Ensure your local `black` installation matches this version, or exclusively rely on `pre-commit` for formatting.
Warnings
- breaking `Black`'s formatting style evolves. If not explicitly pinned, `blacken-docs` (especially in `pre-commit` hooks) may use different `Black` versions, leading to inconsistent formatting or repeated changes.
- gotcha `blacken-docs` exits with a non-zero status code (typically 1) if it modifies any files or encounters parsing errors from `Black`.
- gotcha Using the ellipsis `...` to represent missing code in examples can sometimes cause `Black` to report syntax errors, even though `...` is valid Python.
Install
-
pip install blacken-docs
Quickstart
pip install blacken-docs # Format a specific Markdown file blacken-docs README.md # Format all reStructuredText files in the current directory blacken-docs *.rst # Example .pre-commit-config.yaml entry (recommended): # See https://github.com/adamchainz/blacken-docs for latest revision # - repo: https://github.com/asottile/blacken-docs # rev: v1.20.0 # Use the latest stable tag # hooks: # - id: blacken-docs # additional_dependencies: ['black==24.4.0'] # Pin Black version!