Every Python team eventually runs into the same argument: do we sort imports, where does the closing bracket go, is 79 characters enough, and who gets to decide? The black project ended that debate by refusing to have it. You configure almost nothing, run black ., and every file in the repository comes out looking identical. That tradeoff — no style bikeshedding in exchange for zero flexibility — made it the default formatter for huge swaths of the ecosystem, from small libraries to monorepos that format thousands of files on every commit.
The pain black solves is not stylistic, it is mechanical. Without a deterministic formatter, pull requests carry noise diffs from hand-reformatted code, git blame points at formatting commits instead of logic changes, and code review wastes attention on whitespace. Without an incremental engine, reformatting a large tree on every CI run would be unbearably slow. And without a strict idempotence guarantee, a formatter that produces different output on the second pass would quietly corrupt files. Black answers all three concerns in its source layout: a syntax tree that survives mutation, a line-splitting engine with retryable strategies, and a content-addressed cache that skips files it has already seen.
This post walks the actual tree of psf/black on its main branch, module by module, with every symbol and line number verified against the code. If you have ever wondered how an opinionated formatter can be both ruthless and safe, the answer lives in a handful of files under src/black/ and a legacy parser under src/blib2to3/.
Overview of the black formatter: the CLI layer feeds sources through a pickle cache into the blib2to3 parser, whose syntax tree the line generation core turns into formatted text with help from the splitting engine.
Reading the overview from left to right:
- main, L563 — the argparse entry point that wires configuration into a
Modeobject and collects sources. - get_sources, L846 — resolves directories, globs and stdin, delegating the directory walk to
gen_python_filesinsrc/black/files.py, which honorsGitIgnoreSpecfromget_gitignore(get_gitignore, L256). - Cache, L51 — a pickle-backed cache that splits sources into changed and unchanged sets before any parsing happens.
- lib2to3_parse, L77 — tries one grammar per target version and hands the text to the blib2to3
Driver. - LineGenerator, L121 — a
Visitorsubclass that flattens the whole syntax tree intoLineobjects. - EmptyLineTracker, L592 — the stateful policy that decides how many blank lines belong before and after each emitted line.
- transform_line, L920 — the split dispatcher that tries strategies until an over-long line fits.
- Cache.get_cache_key behind Mode, L335 — the option fingerprint that names the cache file, so changing one flag invalidates only one cache.
The detail view goes one level deeper, exposing the split strategies, the string transformers and the safety checks that keep the formatter honest.
Detailed view: from CLI discovery through parsing, line generation, the splitting engine, string transformers, and the guards — fmt: off handling, line ranges, AST equivalence and stability checks.
From 79-column debates to an 88-column pass
The most quoted number in black is 88: DEFAULT_LINE_LENGTH = 88 is the first line of src/black/const.py. The second and third lines define the default exclude regex (covering .git, .venv, build, dist and friends) and the include regex (\.pyi?|\.ipynb)$ — which explains why black also formats Jupyter notebooks and stub files. The codebase targets Python 3.11 and newer (requires-python = ">=3.11" in pyproject.toml), and the latest tagged release at the time of writing is 26.10.1.
The engine is big. src/black/linegen.py is about 3,245 lines; src/black/trans.py, the string transformer module, is about 2,856 lines; src/black/lines.py holds the Line data structure across roughly 1,895 lines; and the CLI orchestration in src/black/__init__.py is about 1,964 lines. Style evolution is data, not code: the Preview enum in src/black/mode.py lists 33 opt-in features between its start at line 256 and line 293, with exactly two of them (string processing and hug-parens) marked as unstable in UNSTABLE_FEATURES at lines 296 to 301. A nice engineering touch borrowed from Rust lives in the tiny src/black/rusty.py: an Ok/Err/Result wrapper used for error-handling discipline.
Parsing: the CST that remembers whitespace
Black does not use Python’s built-in ast module for formatting. It uses blib2to3, a vendored fork of CPython’s retired lib2to3 package, under src/blib2to3/. The grammar is data: Grammar.txt is a 267-line LL(1) grammar description compiled by pgen; the compiled grammar is pickled next to the package by load_grammar (load_grammar, L241) so cold starts stay fast.
The Driver class (Driver, L116) runs the LL(1) parse over token events and produces a concrete syntax tree built from Node and Leaf objects (src/blib2to3/pytree.py, lines 217 and 421). The crucial property is that the CST preserves everything the ast module throws away: every space, every comment, every blank line lives in the prefix of each leaf. Formatting is therefore not translation into text from scratch — it is prefix surgery on an existing tree, followed by re-serialization.
Because the grammar must accept code from multiple Python versions, lib2to3_parse in src/black/parsing.py collects candidate grammars via get_grammars and tries them in order, raising InvalidInput only when every grammar rejects the input. A separate, stricter safety net exists for the output: stringify_ast compares the ast of source and result, and assert_equivalent (assert_equivalent, L1891) raises ASTSafetyError if formatting ever changed the semantics.
Line generation and splitting: how a line gets fixed
_format_str_once (_format_str_once, L1491) is the single pass everything funnels through. After parsing, it runs normalize_fmt_off to lift # fmt: off regions aside, then instantiates LineGenerator and EmptyLineTracker, and for each line emitted by line_generator.visit(src_node) it asks the tracker how many blank lines precede it, and hands it to transform_line.
LineGenerator subclasses a generic Visitor (Visitor, L146) that walks the tree and dispatches to visit_* methods. Its docstring warns that it destroys the tree it visits by mutating leaf prefixes — a deliberate trade of immutability for speed. The Line object (Line, L49) carries a depth plus an ordered list of leaves, and a BracketTracker instance tracks depth and invisible parens as leaves are appended.
Splitting (transform_line, L920) is a tournament. left_hand_split (left_hand_split, L1112) breaks assignments after the equals sign. right_hand_split (right_hand_split, L1178) — the workhorse — finds the last opening bracket and splits inside it, with right_hand_split_with_omits and generate_trailers_to_omit (line 3059) deciding which trailers to keep on the first line. delimiter_split (delimiter_split, L1852) breaks at top-level commas and operators, and string_concat_split (line 2061) targets implicit string concatenations. The bracket accounting that all of them rely on lives in BracketTracker (BracketTracker, L60), including the delimiter priority logic in max_delimiter_priority_in_atom (line 349).
The distinctive trick is the second opinion. run_transformer (run_transformer, L3174) applies a splitter to a line, then — if the result is still over length and no rule forbids it — re-runs the same splitter with the FORCE_OPTIONAL_PARENTHESES feature so the engine also evaluates the wrapped variant, keeping whichever wins. Combined with the magic trailing comma (a Mode field, magic_trailing_comma: bool = True at line 315 of mode.py), this is how black explodes long calls into one-argument-per-line form deterministically. Whatever the outcome, assert_stable (assert_stable, L1924) re-formats the output and fails the run if a second pass would change anything.
Strings and comments: the escape hatches
Strings are where naive formatters break code, so black quarantines them in src/black/trans.py. The abstract StringTransformer (StringTransformer, L218) defines a protocol with custom split points (CustomSplit, line 325). StringMerger (StringMerger, L414) joins adjacent implicit concatenations first — merging is always safe and often makes splitting unnecessary. StringParenStripper (line 922) removes redundant parens, StringSplitter (line 1572) breaks a long literal at a safe boundary, and StringParenWrapper (line 2020) wraps the concatenation in parentheses when that produces a shorter result. The token-level StringParser (line 2629) rebuilds the split literals back into a syntax tree.
Comments get the same careful treatment in src/black/comments.py. normalize_fmt_off (normalize_fmt_off, L216) converts # fmt: off/# fmt: on regions into standalone-comment placeholders so the splitter never touches their contents, and generate_ignored_nodes (line 819) does the same for per-line # fmt: skip. Line-range formatting — the --line-ranges option used by editors and AI agents to format only a selection — is implemented in src/black/ranges.py: convert_unchanged_lines (convert_unchanged_lines, L186) turns every line outside the requested range into a STANDALONE_COMMENT, which the core then passes through byte-for-byte.
Cache, modes and concurrency
The cache (Cache, L51) is one of the most practical design decisions in the project. Entries are FileData(st_mtime, st_size, sha256) tuples (line 19), stored in a pickle file named cache.<key>.pickle under the user cache directory plus the black version — the key comes from Mode.get_cache_key (Mode.get_cache_key, L335), which joins target versions, line length, every boolean flag and a hashed feature string. Change any option and you get a different cache file; change nothing and is_changed (line 103) short-circuits: size check first, then mtime, and only then a re-hash. Writes are atomic via NamedTemporaryFile plus os.replace (lines 134 to 150).
Every option lives on the Mode dataclass (Mode, L308) — eleven fields from target_versions to enabled_features — which flows through the whole engine as a single value. For large trees, main calls reformat_many (line 824 of __init__.py), which delegates to reformat_many (reformat_many, L89) in src/black/concurrency.py: a process pool whose size is capped by cap_process_pool_workers (line 79), with maybe_use_uvloop (line 32) speeding the event loop where available. The Report class (Report, L24) tallies change_count, same_count and failure_count, maps them to exit codes in return_code (line 73), and even emits GitHub Action outputs via write_github_outputs (line 124).
Black’s own hygiene mirrors its product: the pre-commit configuration pins isort, flake8 and mypy (mirrors-mypy, L20), and the package ships py.typed so downstream users get its annotations checked too. If you enjoy reading type-heavy Python, this codebase pairs well with our mypy source tour; the tokenizer lineage connects directly to CPython’s historical lib2to3; and the notebook support (cell magics are parsed in src/black/handle_ipynb_magics.py) is best understood alongside our ipython internals post.
Honest Limits
- Black is deliberately inflexible: line length, string quote preference and a couple of toggles are the entire configuration surface, by design. If your team needs style variance, black is the wrong tool by its own charter.
- The blib2to3 parser is a fork of a retired CPython module. It is actively maintained, but every new Python syntax (match statements, parenthesized context managers, t-strings) must be added by hand — the
Featureenum inmode.py(line 36) andget_features_used(line 1630 of__init__.py) exist exactly to gate those constructs. - The tree-mutating approach means formatting is not transactional across the whole file:
_format_str_oncerecomputes everything, and stability is enforced only by re-running the pass, not by incremental analysis. - The cache is per-machine and per-version, keyed by
Mode; CI runners that mount no persistent cache will reformat everything each run unless the cache directory is cached between jobs. - Line-range mode converts untouched regions to standalone comments, which means formatting a selection still parses the whole file and depends on the full-file context being parseable.
Enjoyed this post? Never miss out on future posts by following us