Repository navigation
Add blackd-format, a standard-library command-line client for blackd - #5690
Conversation
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.
There was a problem hiding this comment.
🟡 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
| a_lines = a.splitlines(keepends=True) | ||
| b_lines = b.splitlines(keepends=True) |
| 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") |
| else: | ||
| with open(src, "rb") as f: | ||
| data = f.read() | ||
| encoding = tokenize.detect_encoding(io.BytesIO(data).readline)[0] |
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.
|
Pushed 82f4c77, which fixes the CI failures (an unclosed 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
left a comment
There was a problem hiding this comment.
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
IncompleteReador otherHTTPExceptionbecomes 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
--diffon stdin, the labels are-.blackusesSTDIN, which might be worth matching for tools that parse the header. Result.output: str | bytescarries two meanings, diff text or stdin bytes. Two separate fields would be clearer than theisinstancecheck inmain.-taccepts only thepy312form, while blackd itself also takes3.12/py3.12. That matchesblack'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` |
There was a problem hiding this comment.
These sentences belong under the previous header still
|
My only concern is the naming between |
|
@cobaltt7 fair point, the names are close. They do different jobs:
The name comes from #2405, where a "simple Python I pushed eaddcfa. It moves the CORS paragraph back under Usage and adds a sentence to the new section saying how it differs from Drafted with Claude Code; I reviewed it. |
|
I think |
|
@cobaltt7 done in 2864b27. The command is now I left Drafted with Claude Code; I reviewed it. |
# Conflicts: # CHANGES.md
cooperlees
left a comment
There was a problem hiding this comment.
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!

Description
Closes #2405.
Adds
blackd-format, a command-line client for blackd, along the lines agreed with @cooperlees on the issue:blackd_format, because importing anything from theblackdpackage needs aiohttp, and importingblackwould lose most of the startup advantage. A test checks that importing it loads none ofblack,blackd,aiohttporclick. It ships with plainpip install black, with no[d]extra.blackd-format, next toblackandblackd(pluspython -m blackd_format).ThreadPoolExecutor, with at most--workers(default 10) requests in flight. Results print in argument order.BlackDClientis unchanged. It is still the tool for long-running callers that make many async requests.Behaviour follows
blackwhere blackd allows it:-l,-t(repeatable),--pyi,-S,-C,--skip-source-first-line,--preview,--unstable,--enable-unstable-feature,--fast/--safe.--checkand--diffdon't write files. The diff is computed locally with the file paths as labels.-reads stdin and writes the result to stdout.--checkfinds changes, 123 on any error (syntax error, blackd unreachable, HTTP error). One bad file doesn't stop the others.1 file reformatted, 2 files left unchanged.).tokenize.detect_encodingand 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:
pyproject.toml. blackd itself doesn't, andtomllibparsing plus black's config discovery would duplicate code inblack.files..gitignorehandling would mean importing black. Directories are rejected with a message.--pyiand-tare mutually exclusive, becauseX-Python-Variantcan'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/*.pyover 2 KB): "formatted" as they are (blackd answers 204), "messy" afterblack -l 60(blackd reformats them). Plainblackruns with an empty cache dir each time.blackd-format -W 1blackd-format(-W 10)BlackDClient+asyncio.gather, semaphore 10blackStartup on a one-line file (median of 9):
blackd-format0.073 s, aBlackDClientscript 0.227 s,black0.134 s.--workerssweep, 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:
black's and a third of aBlackDClientscript's.urllibin a thread pool is enough.Benchmark script
Checklist - did you ...
--previewstyle, following the stability policy? (no style changes)CHANGES.mdif necessary?I use Claude Code when working on patches; I reviewed and tested everything here before opening the PR.
🤖 Generated with Claude Code