format-python-files — Claude Code hook: auto-format .py with black
This hook runs black on every .py file Claude edits. Formatting stops being a separate step you remember to do.
npx claude-code-templates@latest --hook post-tool/format-python-filesWhat format-python-files does
The hook attaches to PostToolUse with an Edit matcher. After a file change it checks that the path ends in .py and calls black on that file. Whatever Claude wrote into a Python file gets normalized right away.
The whole thing is one line: an extension check plus black "$CLAUDE_TOOL_FILE_PATH" with errors suppressed via 2>/dev/null || true. So a missing black won't break your session, and it also won't format anything. Install it first: pip install black.
It fires on Edit only — not on Write, not on changes made through the terminal. Generate files another way and the formatting stays untouched. Worth checking which tool you actually use to write code.
What it helps with
- format an edited .py file without running black by hand
- kill indentation and quote drift after agent edits
- stop thinking about style mid-session
- settle formatting before code review
Example prompts for the agent
- Fix the parsing function in
parser.pyso it handles nested dicts - Refactor
utils.pyand pull date handling into its own function - Fix the type error in
models.py
How to install format-python-files
1claude-code-templates
npx claude-code-templates@latest --hook post-tool/format-python-files2Manually: put the files in place
.claude/settings.jsonThe hooks block: event (PreToolUse, PostToolUse, Stop…) → command. Personal ones go to ~/.claude/settings.json
Step by step, with commands for each platform: Claude Code hooks: what they are, where to configure them, how to block a risky command
Questions about format-python-files
How do I install format-python-files in Claude?
Run npx claude-code-templates@latest --hook post-tool/format-python-files, then check the entry in .claude/settings.json.
What does format-python-files do?
After every Edit operation it runs black on the changed file when the extension is .py.
What do I need for the hook to work?
black installed: pip install black. Without it the command exits quietly and the file stays unformatted.
Source text
format-python-files.json · MIT
{
"description": "Automatically format Python files after any Edit operation using black formatter. This hook runs 'black' on any .py file that Claude modifies, ensuring consistent Python code formatting. Requires black to be installed ('pip install black'). The command includes error suppression (2>/dev/null || true) so it won't fail if black is not installed.",
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.py ]]; then black \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; fi"
}
]
}
]
}
}
© davila7 · MIT · davila7/claude-code-templates