Skip to content

Add blackd-format, a standard-library command-line client for blackd - #5690

Merged
cooperlees merged 9 commits into
psf:mainfrom
IslamElsayed:blackd-client
Nov 27, 2026
Merged

cooperlees merged 9 commits into
psf:mainfrom
IslamElsayed:blackd-client

Conversation

@IslamElsayed

@IslamElsayed IslamElsayed commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Description

Closes #2405.

Adds blackd-format, a command-line client for blackd, along the lines agreed with @cooperlees on the issue:

  • Standard library only. It lives in its own top-level module, blackd_format, because importing anything from the blackd package needs aiohttp, and importing black would lose most of the startup advantage. A test checks that importing it loads none of black, blackd, aiohttp or click. It ships with plain pip install black, with no [d] extra.
  • Its own entry point, blackd-format, next to black and blackd (plus python -m blackd_format).
  • Several files in parallel. Each file is one request from a ThreadPoolExecutor, with at most --workers (default 10) requests in flight. Results print in argument order.
  • BlackDClient is unchanged. It is still the tool for long-running callers that make many async requests.

Behaviour follows black where blackd allows it:

  • The formatting options map one-to-one to blackd's headers: -l, -t (repeatable), --pyi, -S, -C, --skip-source-first-line, --preview, --unstable, --enable-unstable-feature, --fast/--safe.
  • --check and --diff don't write files. The diff is computed locally with the file paths as labels.
  • - reads stdin and writes the result to stdout.
  • Exit codes: 1 when --check finds changes, 123 on any error (syntax error, blackd unreachable, HTTP error). One bad file doesn't stop the others.
  • The summary line matches black's (1 file reformatted, 2 files left unchanged.).
  • The source encoding is detected with tokenize.detect_encoding and sent as the request charset, so non-UTF-8 files come back in their own encoding.

Things I left out, open to adding them if you want them:

  • It doesn't read pyproject.toml. blackd itself doesn't, and tomllib parsing plus black's config discovery would duplicate code in black.files.
  • It doesn't recurse into directories, because matching black's include/exclude and .gitignore handling would mean importing black. Directories are rejected with a message.
  • --pyi and -t are mutually exclusive, because X-Python-Variant can't carry both.

Benchmark

Wall time per command, process start included, median of 7 runs. One local blackd, 12 CPUs, macOS, Python 3.13.4, every command in check mode. The input is copies of black's own modules (src/black/*.py over 2 KB): "formatted" as they are (blackd answers 204), "messy" after black -l 60 (blackd reformats them). Plain black runs with an empty cache dir each time.

input files blackd-format -W 1 blackd-format (-W 10) BlackDClient + asyncio.gather, semaphore 10 black
formatted 1 0.27 0.30 0.43 0.32
formatted 10 2.05 0.87 1.02 1.06
formatted 100 19.83 3.43 3.68 3.58
messy 1 0.74 0.83 0.99 0.85
messy 10 3.97 1.45 1.57 2.04
messy 100 31.31 5.34 5.51 5.35

Startup on a one-line file (median of 9): blackd-format 0.073 s, a BlackDClient script 0.227 s, black 0.134 s.

--workers sweep, 100 messy files: 2 → 16.3 s, 4 → 8.9 s, 8 → 5.8 s, 10 → 5.4 s, 12 → 5.3 s, 16 → 5.2 s, 24 → 5.5 s, 32 → 5.7 s. Past about 10 the gain flattens: blackd's process pool (one worker per CPU) is the limit, not the client. 10 seemed a sensible default that doesn't flood a smaller machine.

What this shows:

  • For one small file, which is the editor and pre-commit case, the client's startup is what you notice: about half of black's and a third of a BlackDClient script's.
  • On large files, formatting time dominates and all three converge.
  • With many files, threads are at least as fast as the asyncio client. For a one-shot CLI, blocking urllib in a thread pool is enough.
Benchmark script
"""Wall time of blackd-format vs an asyncio BlackDClient script vs plain black.

usage: bench.py <venv-bin> <black-checkout> <out-dir>
Starts blackd on a free port, builds file sets, and times each command end to end
(process start included) with --check-like semantics: nothing is written back.
"""

import os
import shutil
import socket
import statistics
import subprocess
import sys
import tempfile
import time
from pathlib import Path

BIN, REPO, OUT = map(Path, sys.argv[1:4])
RUNS = 7
SIZES = (1, 10, 100)

ASYNC_SCRIPT = """
import asyncio, sys
from blackd.client import BlackDClient

async def main(url, paths):
    client = BlackDClient(url=url)
    sem = asyncio.Semaphore(10)
    async def one(p):
        async with sem:
            with open(p, encoding="utf-8") as f:
                return await client.format_code(f.read())
    await asyncio.gather(*(one(p) for p in paths))

asyncio.run(main(sys.argv[1], sys.argv[2:]))
"""


def free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def build_sets() -> dict[str, list[str]]:
    # Real-world input: black's own modules, which are already formatted (204), and
    # the same modules squeezed to 60 columns, which need reformatting (200).
    sources = sorted((REPO / "src" / "black").glob("*.py"))
    sources = [p for p in sources if p.stat().st_size > 2000]
    formatted_dir = OUT / "formatted"
    messy_dir = OUT / "messy"
    for d in (formatted_dir, messy_dir):
        shutil.rmtree(d, ignore_errors=True)
        d.mkdir(parents=True)
    paths: dict[str, list[str]] = {"formatted": [], "messy": []}
    for i in range(max(SIZES)):
        src = sources[i % len(sources)]
        f = formatted_dir / f"{i:03d}_{src.name}"
        shutil.copy(src, f)
        paths["formatted"].append(str(f))
        m = messy_dir / f.name
        shutil.copy(src, m)
        paths["messy"].append(str(m))
    subprocess.run([BIN / "black", "-q", "-l", "60", *paths["messy"]], check=True)
    return paths


def timed(cmd: list[str], env: dict[str, str] | None = None) -> float:
    samples = []
    for _ in range(RUNS):
        start = time.perf_counter()
        subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
        samples.append(time.perf_counter() - start)
    return statistics.median(samples)


def main() -> None:
    port = free_port()
    url = f"http://127.0.0.1:{port}"
    server = subprocess.Popen(
        [BIN / "blackd", "--bind-host", "127.0.0.1", "--bind-port", str(port)],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    try:
        for _ in range(100):
            try:
                socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
                break
            except OSError:
                time.sleep(0.1)
        sets = build_sets()
        python = str(BIN / "python")
        # Warm blackd's process pool so the first timed run isn't penalised.
        subprocess.run([BIN / "blackd-format", f"--url={url}", "--check", "-q", *sets["messy"][:20]])
        print(f"median of {RUNS} runs, seconds; {os.cpu_count()} CPUs; Python {sys.version.split()[0]}")
        print("| input | files | blackd-format -W 1 | blackd-format (-W 10) | BlackDClient + asyncio (sem 10) | black |")
        print("| --- | ---: | ---: | ---: | ---: | ---: |")
        for kind in ("formatted", "messy"):
            for n in SIZES:
                files = sets[kind][:n]
                one = timed([str(BIN / "blackd-format"), f"--url={url}", "--check", "-q", "-W", "1", *files])
                ten = timed([str(BIN / "blackd-format"), f"--url={url}", "--check", "-q", *files])
                aio = timed([python, "-c", ASYNC_SCRIPT, url, *files])
                cache = tempfile.mkdtemp()
                env = {**os.environ, "BLACK_CACHE_DIR": cache}
                # A fresh cache dir per run so black really formats every time.
                samples = []
                for _ in range(RUNS):
                    shutil.rmtree(cache, ignore_errors=True)
                    start = time.perf_counter()
                    subprocess.run(
                        [str(BIN / "black"), "--check", "-q", *files],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env,
                    )
                    samples.append(time.perf_counter() - start)
                blk = statistics.median(samples)
                print(f"| {kind} | {n} | {one:.2f} | {ten:.2f} | {aio:.2f} | {blk:.2f} |", flush=True)
    finally:
        server.terminate()
        server.wait()


if __name__ == "__main__":
    main()

Checklist - did you ...

  • Implement any code style changes under the --preview style, following the stability policy? (no style changes)
  • Add an entry in CHANGES.md if necessary?
  • Add / update tests if necessary?
  • Add new / update outdated documentation?

I use Claude Code when working on patches; I reviewed and tested everything here before opening the PR.

🤖 Generated with Claude Code

IslamElsayed and others added 3 commits November 13, 2026 16:07
It formats several files in parallel, one request per file from a thread
pool capped by --workers (default 10), and only imports the standard
library, so it starts faster than black and needs no [d] extra.
@cooperlees
cooperlees requested review from cooperlees and a balanced review from Copilot November 13, 2026 16:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved issues can produce invalid patches, leave truncated HTTP response errors uncaught, and misdetect source encoding when the first line is skipped.

4 open issues
What changed in this PR

Adds blackd-client, a standard-library command-line client for formatting files through a running blackd server, addressing #2405 without changing the existing asynchronous BlackDClient.

Changes:

  • Adds parallel file formatting, stdin support, local diffs, check mode, and formatting options mapped to blackd headers.
  • Registers standalone and module entry points without requiring the [d] extra.
  • Adds tests, usage documentation, and a changelog entry.
File Description
tests/​test_blackd_client.py Tests dependency isolation, options, formatting, errors, and source encoding.
src/​blackd_client/​__main__.py Enables python -m blackd_client.
src/​blackd_client/​__init__.py Implements requests, parallel processing, diffs, and reporting.
pyproject.toml Registers the command and updates compilation and import-sorting configuration.
docs/​usage_and_configuration/​black_as_a_server.md Documents client usage, options, and limitations.
CHANGES.md Announces the new command-line client.

Review effort: Balanced

Comment thread src/blackd_client/__init__.py Outdated
Comment on lines +100 to +101
a_lines = a.splitlines(keepends=True)
b_lines = b.splitlines(keepends=True)
Comment thread src/blackd_client/__init__.py Outdated
lines = []
for line in difflib.unified_diff(a_lines, b_lines, a_name, b_name, n=5):
# Like black's own --diff, end the last line even if the file doesn't.
lines.append(line if line.endswith("\n") else line + "\n")
Comment thread src/blackd_client/__init__.py Outdated
else:
with open(src, "rb") as f:
data = f.read()
encoding = tokenize.detect_encoding(io.BytesIO(data).readline)[0]
Comment thread src/blackd_client/__init__.py Resolved
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

diff-shades results comparing this PR (04b5ebe) to main (1e4ab75):

--preview style: no changes

--stable style: no changes


What is this? | Workflow run | diff-shades documentation

Close the HTTPError response after reading it; the leaked response was
reported as a ResourceWarning on 3.14+, Windows and PyPy. Read and write
test files as bytes so Windows newline translation doesn't change them, and
give the import check an explicit encoding and the inherited environment.

From the review: build --diff output like black.output.diff (no splitting
on form feeds, the 'No newline at end of file' marker), detect the encoding
after the line skipped by --skip-source-first-line as black does, and report
errors raised while reading a response, such as IncompleteRead, per file.
@IslamElsayed

Copy link
Copy Markdown
Contributor Author

Pushed 82f4c77, which fixes the CI failures (an unclosed HTTPError response, CRLF in the Windows diff test, a missing encoding= in the import test) and the four Copilot findings. Could someone approve the workflow run again? Thanks for the first one.

Drafted with Claude Code; I reviewed it.

The Windows ProactorEventLoop leaves the socket for a pending AcceptEx
unclosed at shutdown. PyPy collects it later and reports an unraisable
ResourceWarning in an unrelated test (test_format on pypy3.12/windows).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@cooperlees cooperlees left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a clean implementation of what we discussed in #2405. Standard library only, with a test that guards it, and no changes to BlackDClient. The benchmark is useful and supports the default of 10 workers.

I've checked that the four Copilot findings are fixed in 82f4c77:

  • The diff splits only on CR/LF/CRLF, copying _splitlines_no_ff.
  • Files without a trailing newline get the "No newline at end of file" marker.
  • The encoding cookie is read after the line skipped by --skip-source-first-line.
  • An IncompleteRead or other HTTPException becomes a per-file error.

The parametrized test against black.output.diff is a nice touch.

I pushed one commit (87152f3) to fix the pypy3.12 / windows-latest failure. On Windows, asyncio.new_event_loop() gives a ProactorEventLoop. It pre-creates a socket for the pending AcceptEx, and that socket isn't closed when the fixture shuts the loop down. PyPy collects it later, so the ResourceWarning shows up in an unrelated test (test_format). The test server fixture now uses asyncio.SelectorEventLoop().

Some non-blocking nits, fine as follow-ups or not at all:

  • With --diff on stdin, the labels are -. black uses STDIN, which might be worth matching for tools that parse the header.
  • Result.output: str | bytes carries two meanings, diff text or stdin bytes. Two separate fields would be clearer than the isinstance check in main.
  • -t accepts only the py312 form, while blackd itself also takes 3.12 / py3.12. That matches black's CLI, so I'm fine with it, but maybe mention it in the help text.

LGTM, thanks!


```

Cross-origin browser requests are rejected by default. If you need to access `blackd`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These sentences belong under the previous header still

@cobaltt7

Copy link
Copy Markdown
Collaborator

My only concern is the naming between BlackDClient and blackd_client - the difference, implementation, and purpose of each seems confusing and conflicting

@IslamElsayed

Copy link
Copy Markdown
Contributor Author

@cobaltt7 fair point, the names are close. They do different jobs:

  • BlackDClient (blackd.client, Implement blackd python client #4774) is an asyncio library for Python programs. It needs aiohttp, so it comes with the [d] extra.
  • blackd-client is a command-line tool that only uses the standard library. It installs with plain black and starts in about a third of the time a BlackDClient script takes (0.073s vs 0.227s in the description's benchmark).

The name comes from #2405, where a "simple Python blackd-client" was what had been asked for.

I pushed eaddcfa. It moves the CORS paragraph back under Usage and adds a sentence to the new section saying how it differs from BlackDClient. If that's still confusing, I'm happy to rename the command and module, for example to blackd-format / blackd_format. Which would you prefer?

Drafted with Claude Code; I reviewed it.

@cobaltt7

Copy link
Copy Markdown
Collaborator

I think blackd-format would be an appropriate name. "Client" feels vague to me. Not sure we should consider renaming BlackDClient as well, or what a better name would be, but it's probably fine

@IslamElsayed IslamElsayed changed the title Add blackd-client, a standard-library command-line client for blackd Add blackd-format, a standard-library command-line client for blackd Nov 18, 2026
@IslamElsayed

Copy link
Copy Markdown
Contributor Author

@cobaltt7 done in 2864b27. The command is now blackd-format and the module blackd_format, across the code, tests, docs and changelog. I'll update the PR title and description to match.

I left BlackDClient as it is. Renaming it would break existing imports, so it would need its own deprecation if anyone wants that.

Drafted with Claude Code; I reviewed it.

@cobaltt7 cobaltt7 added this to the Backlog milestone Nov 25, 2026

@cooperlees cooperlees left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed after the rename and the merge from main. The changes since my last approval are the docs fix for @cobaltt7's CORS comment, the note telling blackd-format apart from BlackDClient, and the blackd-client → blackd-format rename. The rename is complete and mechanical: entry point, module, mypyc exclude, isort config, tests, docs and changelog. The code is otherwise unchanged and CI is green.

The earlier nits (the STDIN diff label, splitting Result.output, help text for -t) are still fine as follow-ups.

LGTM, thanks @IslamElsayed!

@cooperlees
cooperlees merged commit 573c81e into psf:main Nov 27, 2026
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Simple CLI "client" For blackd

4 participants