Home › Developer Tools › Python Formatter

Python Formatter

Paste messy Python and get clean, consistently formatted code in the style used by Black and Ruff: normalised spacing and quotes, two blank lines around top-level functions and classes, and long lines split at brackets. Choose the line length, quote style and indent.

Last updated:

Advertisement
Advertisement

How to use the Python Formatter

  1. Paste your Python code into the left box, upload a .py file, or click Sample.
  2. Choose the options: line length (88 is the Black and Ruff default), quote style and indent width.
  3. Read the result on the right; it updates as you type and the status line shows how many lines changed.
  4. Fix syntax errors if the formatter reports one, such as an unclosed bracket or string.
  5. Copy or download the formatted code as a .py file.

What the formatter changes

BeforeAfterRule
x=1+2*yx = 1 + 2 * ySpaces around assignment and binary operators
f(a , b ,c)f(a, b, c)No space before a comma, one after
def f(a = 1, *args, b : int=2)def f(a=1, *args, b: int = 2)No spaces around keyword defaults unless annotated
x ** 2, f(x)**2x**2, f(x) ** 2Power operator hugs simple operands only
ham[lower+offset:upper]ham[lower + offset : upper]Slice colons act like operators when an operand is complex
'text', u'x', 0XFF, 1E5"text", "x", 0xFF, 1e5Preferred quotes and normalised prefixes and numbers
if x: return yif x: / return y on its own lineOne statement per line
x = 1 # notex = 1 # noteTwo spaces before an inline comment, one after #
class A():class A:Redundant parentheses removed

How long lines are split

When a line is longer than the limit, the formatter first tries to split at the last opening bracket: the content goes on its own indented line, and the closing bracket returns to the original indentation. If the content still does not fit, it is split at the highest-priority delimiter: commas first (one item per line, with a trailing comma added), then comprehension clauses, conditional expressions, and/or, comparisons and arithmetic operators, with each operator starting a new line. Long right-hand sides of assignments and return statements are wrapped in parentheses so no backslashes are needed.

result = load_config("settings.env", defaults={"mode": "production", "debug": "false"}, strict=True)

# becomes (line length 88)
result = load_config(
    "settings.env", defaults={"mode": "production", "debug": "false"}, strict=True
)

Using the same style in your project

  • Install a formatter with pip install black or pip install ruff and run black . or ruff format . in your project folder.
  • Set the line length once in pyproject.toml: [tool.black] line-length = 100 or [tool.ruff] line-length = 100.
  • Use quote-style = "single" under [tool.ruff.format] if your team prefers single quotes; Black itself only supports double quotes (or leaving them unchanged with --skip-string-normalization).
  • Add the formatter to a pre-commit hook or your editor's format-on-save so code stays consistent without manual effort.

Frequently asked questions

What style does this Python formatter use?

It follows the Black code style, which Ruff's formatter also implements: 4-space indentation, double quotes, spaces around operators and after commas, two blank lines around top-level functions and classes, and lines wrapped at 88 characters by splitting inside brackets. Code formatted here matches what black or ruff format would produce in the vast majority of cases.

What is the difference between Black and Ruff format?

Black is the original opinionated Python formatter written in Python. Ruff is a much faster linter and formatter written in Rust whose formatter is designed as a drop-in replacement for Black and produces nearly identical output. This page runs Ruff compiled to WebAssembly when it can load, and otherwise a built-in JavaScript formatter that applies the same rules.

What is a magic trailing comma?

If a collection or argument list ends with a comma, as in foo(a, b,), Black and Ruff keep it exploded with one item per line even when it would fit on one line. This lets you choose the vertical layout for lists that change often. Untick the option to collapse such lists when they fit.

Does formatting change what my code does?

No. Formatters only change whitespace, line breaks, redundant parentheses, quote characters and the case of number prefixes, so the program's syntax tree stays the same. Black verifies this by comparing the AST before and after formatting, and the built-in engine here was tested the same way on the Python standard library.

Why is a long line not split?

Lines are split only at brackets, operators and commas. A single long string, a long comment or a long name cannot be broken without changing the code, so the formatter leaves it as it is. Wrap long strings yourself with implicit concatenation inside parentheses.

Is it PEP 8 compliant?

The output follows PEP 8 for indentation, whitespace and blank lines. Black's default line length is 88 instead of PEP 8's 79; pick 79 in the options if your project requires it.

Is my code uploaded?

No. Formatting runs entirely in your browser, either with the Ruff WebAssembly module or the built-in engine, so private code never leaves your device.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JSON to Python ClassGenerate Python dataclasses, Pydantic models or TypedDicts with type hints from JSON.JavaScript BeautifierFormat and beautify messy or minified JavaScript, or minify it.SQL Formatter & BeautifierFormat, beautify or minify SQL queries for MySQL, PostgreSQL and more.Code Diff CheckerCompare two code files side by side or unified, with syntax colors and changes highlighted.JavaScript Object to JSONTurn JS object literals and Python dicts into valid JSON: quotes keys, fixes commas and values.JSON FormatterBeautify, minify and validate JSON, with a collapsible tree view.HTML FormatterBeautify and indent HTML code with a live preview.CSS FormatterBeautify CSS with indent controls and optional property sorting.XML FormatterBeautify, validate and minify XML with a collapsible tree view.ZIP File CreatorCompress files and folders into a ZIP.YAML Validator & FormatterValidate, format and minify YAML, and convert YAML to JSON or back.HTML MinifierMinify HTML: strip comments and whitespace safely and see how many bytes you save.CSS MinifierMinify CSS with csso or a built-in engine and see the size saved instantly.JavaScript MinifierMinify JavaScript with Terser: compress, mangle and see how many bytes you save.JSON MinifierMinify and validate JSON, sort keys and see exactly how many bytes you save.IPv6 Expander & CompressorExpand IPv6 addresses to full form or compress them per RFC 5952, one or many at once.GraphQL FormatterPretty-print and indent GraphQL queries, mutations and schemas, or minify them, instantly.CSS ValidatorValidate CSS: syntax errors, unknown properties and invalid values by line, plus auto-fix.Gzip Compress / DecompressGzip or deflate text and files, get Base64 output, and decompress Base64 or .gz files.IBAN ValidatorCheck an IBAN's mod-97 checksum, country and length, and see its bank code and account parts.JavaScript Syntax CheckerCheck JavaScript for syntax errors with line and column, for any ES version, script or module.JSON Schema ValidatorValidate JSON against a JSON Schema (draft-07, 2019-09, 2020-12) with clickable error paths.Markdown FormatterBeautify Markdown with Prettier: list markers, prose wrap, aligned tables and live preview.PHP FormatterBeautify PHP code with Prettier PHP: PSR-12 style, indent and brace options, syntax errors.TypeScript FormatterFormat TypeScript and TSX code with Prettier: width, tabs, semicolons and quotes options.XML MinifierMinify and validate XML: strip whitespace and comments, keep CDATA, see the size savings.C# FormatterBeautify C# code online: Allman or K&R braces, indent size and line width, clang-format option.HTML ValidatorCheck HTML for errors and warnings with line numbers, locally or with the W3C Nu checker.Java FormatterBeautify Java code online: indent size, brace style and line width, with clang-format option.JavaScript ObfuscatorObfuscate JavaScript with string encoding, renaming and control-flow flattening presets.Phone Number FormatterFormat and validate lists of phone numbers to E.164, international or national style.Responsive Design CheckerPreview any website at phone, tablet, laptop and desktop sizes side by side, with rotate and zoom.Browser Compatibility CheckerSearch CSS, JavaScript and HTML features and see which browser versions support them.Core Web Vitals CheckerCheck real-user LCP, INP and CLS for any URL or site and see if it passes Core Web Vitals.Heading Structure CheckerPaste HTML to see its H1-H6 outline and catch missing H1s, multiple H1s and skipped levels.Website Hosting CheckerFind out who hosts a website: hosting provider, IP addresses, ASN, network owner and location.Routing Number ValidatorCheck a US ABA routing number's checksum and format and see its Federal Reserve district.Spam Word CheckerScan an email subject and body for spam trigger words, excess caps, exclamation marks and risky links.XSD ValidatorValidate XML against an XSD schema in your browser and see each error with its line number.Strftime Format BuilderBuild Python and C strftime format strings by clicking tokens, with a live preview and reference.Check Digit CalculatorCalculate or validate check digits for UPC, EAN, GTIN, SSCC, ISBN, ISSN and mod 11 codes.Luhn Algorithm CheckerValidate numbers with the Luhn mod 10 check or calculate the missing check digit, step by step.
See all 41 Code Formatters & Validators →