Python Formatter
Formatters & BeautifiersFormat Python code with Black-compatible style — PEP 8 compliant, consistent. Free, private — all processing in your browser.
The Python Formatter beautifies Python code using Black-compatible formatting — the opinionated code style that has become standard for modern Python projects. Black eliminates style debates by having one canonical format. This tool applies the same rules: 88-character line width (Black default, slightly wider than PEP 8 80-char), 4-space indentation (PEP 8), double quotes (Black preference), trailing commas where appropriate, consistent spacing around operators, and f-string handling. Supports Python 3 syntax including type hints, async/await, walrus operator, match statements, and decorators.
Python code style matters because Python has the richest set of formatting options of any popular language — multiple ways to do everything. Without a consistent style, team code becomes hard to read. Black (started 2018, now the de facto standard) eliminates debates by being opinionated. Major projects using Black: FastAPI, Django-Ninja, Poetry, pipx, Pydantic, Hypothesis. This formatter applies the same style without installing Black locally. Perfect for quick cleanups, code reviews, or teams adopting Black.
Python Formatter — key features
Black-compatible formatting
Same rules as Black. Output matches what Black produces in terminal.
Python 3 support
Type hints, f-strings, walrus, match statements, async/await — all modern features.
Configurable line width
88 (Black default), 80 (PEP 8), 120 (Django). Match your project.
Trailing commas
Added in multi-line collections for clean git diffs. Removed if single-line fits.
Docstring preservation
Docstrings not reformatted — Black leaves them alone. Use docformatter for docstring-specific formatting.
Import preservation
Order not changed (use isort for that). Formatter focuses on style only.
Modern Python features
Walrus operator (3.8+), match statements (3.10+), PEP 695 type syntax (3.12+).
100% client-side
Your Python (business logic, ML code, internal scripts) stays in browser.
How to use the Python Formatter
- 1
Paste Python code
From file, notebook, or clipboard. Python 3 code supported.
- 2
Set line width
88 (Black default), 80 (PEP 8), or your project preference.
- 3
Click Format
Cleanly formatted Python following Black rules.
- 4
Copy or download
Save as .py file or paste into your editor.
Common use cases for the Python Formatter
Code quality
- →Apply Black style: Adopt Black in a legacy codebase. Format file by file.
- →PR preparation: Format before committing so reviewers focus on logic.
- →Code review: Format paste from Slack or email before reviewing.
Common Python projects
- →Django/FastAPI projects: Most modern Python web frameworks use Black.
- →Data science / ML: Notebooks and ML pipelines benefit from consistent formatting.
- →CLI tools: Click, Typer-based CLIs.
- →Libraries: Published Python libraries ship formatted code.
Learning
- →Teach Python style: Show students Black output — learn by example.
- →Compare your style to Black: See how you differ. Usually educational.
Migration
- →Python 2 to 3: Format as you migrate — ensures clean result.
- →Flake8 to Black: Eliminate style debates by adopting Black.
- →Legacy code modernization: Format old codebases to current style.
Python Formatter — examples
Basic function
Type hints and docstring.
def greet(name:str,greeting:str="Hello")->str:
return f"{greeting}, {name}!"def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"Long function signature
Wrapped to multi-line.
def process_user_data(user_id: int, full_name: str, email_address: str, preferences: dict, timezone: str = "UTC") -> dict:
passdef process_user_data(
user_id: int,
full_name: str,
email_address: str,
preferences: dict,
timezone: str = "UTC",
) -> dict:
passList comprehension
Python idiomatic.
users=[u.name for u in session.query(User).filter(User.active==True).order_by(User.name).all() if u.email]
users = [
u.name
for u in session.query(User).filter(User.active == True).order_by(User.name).all()
if u.email
]Class with type hints
Dataclass-style class.
from dataclasses import dataclass
@dataclass
class User:
id:int
name:str
email:str|None=Nonefrom dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: str | None = NoneAsync function
async/await preserved.
async def fetch_users(limit:int=10)->list[User]:
async with session.get("/users") as response:
data=await response.json()
return [User(**u) for u in data[:limit]]async def fetch_users(limit: int = 10) -> list[User]:
async with session.get("/users") as response:
data = await response.json()
return [User(**u) for u in data[:limit]]Match statement
Python 3.10+ pattern matching.
match command:
case "help": show_help()
case "exit": sys.exit(0)
case _: run_command(command)match command:
case "help":
show_help()
case "exit":
sys.exit(0)
case _:
run_command(command)Technical details
Black-style formatting (opinionated, based on PEP 8 with some modifications):
Line width: 88 characters (default). Slightly wider than PEP 8 80-char. Configurable.
Indentation: 4 spaces per level (PEP 8).
Quote style: Double quotes "string" preferred (Black decision). Single quotes converted unless single would avoid escapes.
Trailing commas: Added in multi-line collections — makes diffs cleaner:
``python``
items = [
"one",
"two",
"three", # <- trailing comma
]
Magic trailing comma: If you add trailing comma, Black keeps multi-line. Without it, Black collapses to single line if fits.
Function signatures:
Short fits on one line:
``python``
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
Long breaks onto multiple lines:
``python``
def process_user_data(
user_id: int,
full_name: str,
email_address: str,
preferences: dict[str, Any],
timezone: str = "UTC",
) -> dict[str, Any]:
pass
Imports:
Black does not sort imports (that is isort territory). Preserves order. Groups:
```python
# Standard library
import os
import sys
# Third-party
import requests
from django.db import models
# Local
from .utils import helper
```
F-strings:
``python``
name = "Alice"
greeting = f"Hello, {name}!"
Formatter preserves f-string contents. Black does not reformat expressions inside f-strings (except spacing).
Type hints:
``python``
def calculate(
items: list[dict[str, int]],
threshold: int = 10,
) -> tuple[int, list[str]]:
pass
Complex type hints formatted for readability. Union types: Optional[X] and X | None both preserved.
Modern Python features (Black 23+):
- Walrus operator: while chunk := f.read(1024):
- Match statements (Python 3.10+): match command:
- ParamSpec/TypeVarTuple: type hint features.
Comments:
- # line comments preserved in position.
- """docstrings""" preserved — contents not reformatted (Black does not touch docstrings).
- Shebang #! preserved.
Docstrings:
``python``
def calculate(x: int, y: int) -> int:
"""
Calculate the sum of two integers.
Args:
x: First integer
y: Second integer
Returns:
The sum x + y
"""
return x + y
Black preserves docstring exactly. Tools like docformatter or pydocstyle handle docstring-specific formatting.
What Black does NOT do:
- Sort imports (use isort).
- Remove unused imports (use autoflake, pyflakes, ruff).
- Add missing docstrings.
- Fix type errors (use mypy).
- Fix logic bugs (use pytest, Hypothesis).
Line length:
88 is Black default. PEP 8 says 79. Django uses 119. Google uses 80. Match your project setting.
Common problems and solutions
⚠Black changes my preferred style
Black is opinionated by design. You adopt its style, not vice versa. Benefits: no style debates, consistent team code. If you disagree, use autopep8 or yapf which are more configurable.
⚠Line length surprises
Black default is 88 (wider than PEP 8's 79). Your team may use different setting. Configure line length to match.
⚠Black adds trailing commas everywhere
The magic trailing comma feature — if you put a trailing comma, Black keeps items on separate lines. Without trailing comma, Black tries to fit on one line.
⚠Docstrings not formatted
Black does not format docstring contents. Use docformatter or pydocstyle for that. Black only formats code around docstrings.
⚠Imports not sorted
Black does not sort imports. Use isort (often ran alongside Black) to sort imports by group (stdlib, third-party, local).
⚠String quote conversion
Black prefers double quotes but keeps single if it avoids escapes. `"can't"` stays as is (has apostrophe). `"hello"` converted from `'hello'`.
⚠Complex generic types
Generic types can get long (dict[str, list[dict[str, int]]]). Black wraps sensibly but may not match your preferred style. Consider TypeAlias for complex types.
⚠Two blank lines between functions
Standard Python style: 2 blank lines before top-level function/class definitions. Black enforces this. Some teams prefer 1 — Black not configurable here.
Python Formatter — comparisons and alternatives
Black vs autopep8: Black is opinionated (one way). autopep8 is configurable. Black is the modern standard; autopep8 is older alternative. Black wins on consistency, autopep8 on flexibility.
Black vs yapf: yapf (Google) is configurable in complex ways. Black is simpler (fewer knobs). Black has more adoption.
Black vs Ruff format: Ruff is a modern Rust-based linter that also formats (100x faster than Black). Black-compatible output. For large codebases, Ruff is faster.
Python Formatter vs Linter: Formatter fixes style. Linter (Flake8, Ruff, Pylint) fixes semantic issues (unused imports, missing docstrings, errors). Use both.
Python Formatter vs Type Checker: Formatter changes whitespace. Type checker (mypy, pyright, pyre) checks type correctness. Orthogonal — use both.
PEP 8 vs Black: PEP 8 is the Python style guide. Black follows PEP 8 mostly but diverges on line length (88 vs 79), trailing commas, and other details. Black is PEP 8 compliant with modern extensions.
Frequently asked questions about the Python Formatter
▶What is Black formatting?
Black is an opinionated Python code formatter that has become the de facto standard since ~2019. Applies one canonical style to eliminate debates. Major users: FastAPI, Django-Ninja, Pydantic, Poetry. This tool produces Black-compatible output.
▶Why is Black line length 88 not 80?
Black team chose 88 as a slight compromise — wider than PEP 8 80 but still keeps code readable side-by-side. 88 chars fits 2 files in typical wide-screen monitors. Configurable in .toml config.
▶Is my Python code safe here?
Yes. Formatting in your browser. No upload. Safe for proprietary business logic, ML code, data pipelines.
▶Does it support Python 2?
This tool targets Python 3. Python 2 reached end-of-life 2020. If you still maintain Python 2 code, use a Python 2-compatible formatter (autopep8 with --python2 flag).
▶What about my custom style preferences?
Black is opinionated — you adopt its style. Small configs: line length, target version. For more flexibility, use yapf or autopep8 which are highly configurable.
▶Does it sort imports?
No. Black preserves import order. Use isort for import sorting. Typical workflow: isort file.py && black file.py. Ruff can do both in one step.
▶What about docstrings?
Preserved exactly — not reformatted. Black leaves docstrings alone. For docstring-specific formatting (line length, quote style), use docformatter.
▶Can I format type hints?
Yes. Complex generics break onto multiple lines when needed. Union types (X | Y) and Optional preserved. Modern Python 3.12+ type syntax supported.
▶What about f-strings?
F-string contents preserved. Black does not reformat expressions inside f-strings (aside from basic spacing). Spacing outside f-strings normalized.
▶Does it work on Jupyter notebooks?
Not directly — format cells individually. For notebooks, use nbqa (runs Black on notebook cells) or jupyter-black extension.
Additional resources
- Black — The opinionated Python formatter.
- PEP 8 — Python Style Guide — Official Python style conventions.
- isort — Import sorter, used with Black.
- Ruff — Fast Rust-based Python linter and formatter.
- Python for Beginners (Tooleras blog) — Our Python tutorial.
Related tools
All Formatters & BeautifiersCSS Formatter
Beautify and indent CSS, SCSS, LESS code — configurable style, production-ready output
HTML Formatter
Format, indent, and beautify HTML, XHTML, and HTML5 markup
JavaScript Formatter
Beautify JavaScript, TypeScript, JSX with Prettier-style formatting
JSON Formatter
Format, validate, and beautify JSON instantly in your browser
JSON to YAML Converter
Convert JSON to YAML or YAML to JSON — preserves structure, nested objects
SQL Formatter
Format and beautify SQL queries for any dialect (MySQL, PostgreSQL, etc.)
Learn more
Explore more tools
200+ free tools that run in your browser.
Browse all tools →