black β Python Code Formatter#
What it is#
black is the opinionated Python code formatter. It enforces a single, consistent style with minimal configuration. The goal: stop debating formatting in code review forever. What black produces is the style.
[!NOTE] For new projects, consider ruff format instead β it implements black-compatible formatting and combines linting in one tool. Black remains the gold standard and is still widely used in existing projects.
Install#
pip install black
Quick example#
# messy.py (before black)
x = {'a':1,'b':2}
def foo(x,y,z):
return x+y+z
result=foo(1,2,3)
black messy.py
Output:
reformatted messy.py
All done! β¨ π° β¨
1 file reformatted.
After black:
x = {"a": 1, "b": 2}
def foo(x, y, z):
return x + y + z
result = foo(1, 2, 3)
When / why to use it#
- Existing projects already using black β keep using it, no migration needed.
- Teams that want zero configuration and a single authoritative style.
- When you want the black badge on your README to signal consistent formatting.
Common pitfalls#
[!WARNING] black reformats strings to double quotes β if your codebase uses single quotes extensively, the first run will produce a large diff. This is expected and only happens once. Commit the reformatted code and move on.
[!WARNING]
--checkvs no flag βblack --checkreports whether files would change but does not change them (exit code 1 if any file would be reformatted). Runningblackwithout--checkmodifies files in place.
[!TIP] Use
# fmt: offand# fmt: oncomments to disable black for specific blocks (e.g. hand-aligned tables or magic number arrays). Use sparingly.
Richer example β check mode in CI#
# CI: fail if code is not already black-formatted
black --check --diff src/
Output (when files need formatting):
--- src/utils.py 2026-04-25 09:00:00
+++ src/utils.py 2026-04-25 09:00:00
@@ -1,3 +1,6 @@
-def foo(x,y): return x+y
+def foo(x, y):
+ return x + y
+
would reformat src/utils.py
Oh no! π₯ π π₯
1 file would be reformatted.
Output (when all files are formatted):
All done! β¨ π° β¨
5 files would be left unchanged.
pyproject.toml configuration#
Black has intentionally minimal config. The only common options:
[tool.black]
line-length = 88 # default; increase if your team prefers longer lines
target-version = ["py312"]
skip-string-normalization = false
exclude = '''
/(
\.git
| dist
| build
| \.venv
)/
'''
Editor integration#
| Editor | Plugin |
|---|---|
| VS Code | Python extension β set "editor.defaultFormatter": "ms-python.black-formatter" |
| PyCharm | Settings β Tools β Black |
| Neovim | conform.nvim or null-ls |
| Emacs | blacken-mode |
Pre-commit hook#
# .pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 24.4.2
hooks:
- id: black
pip install pre-commit
pre-commit install
After this, black runs automatically before every commit. If it reformats any file the commit is aborted β re-stage the reformatted files and commit again.