Editor

Python code formatter

Tidy Python code with Black, the formatter most Python projects use.

Your code

import sys,os
from math import sqrt,pi
def area( r ):
return pi*r **2
class Point :
def __init__(self,x,y): self.x=x;self.y=y
def distance(self,other) :
return sqrt((self.x-other.x)**2+(self.y-other.y)**2)
points=[Point(0,0),Point(3,4),Point( 6 , 8 )]
names = {'origin':points[0],'middle':points[1],'far':points[2],'a_much_longer_name':Point(10,10)}
print( area(2) , points[0].distance(points[1]) )

Formatted

Formatting...

Open in the editor

What the formatter changes

Spaces around operators and after commas

Before

total=price*qty+tax
print(a,b)

After

total = price * qty + tax
print(a, b)

Double quotes for strings

Before

name = 'Asha'

After

name = "Asha"

Long lines split inside brackets

Before

scores = {'asha': 91, 'ben': 78, 'chen': 85, 'dev': 66, 'eli': 93, 'fay': 70, 'gus': 88, 'hana': 74}

After

scores = {
    "asha": 91,
    "ben": 78,
    "chen": 85,
    "dev": 66,
    "eli": 93,
    "fay": 70,
    "gus": 88,
    "hana": 74,
}

Blank lines around functions and classes

Before

import math
def area(r):
  return math.pi*r**2

After

import math


def area(r):
    return math.pi * r**2

To find errors and likely bugs rather than layout, use the Python code checker. The style rules themselves are in Writing clean Python.

Questions

Does formatting change what my code does?

No. Black only changes layout: spaces, line breaks, quotes and brackets. It checks that the formatted code means exactly the same as the original before it gives it back.

What is Black?

Black is the Python formatter most open-source projects and companies use. It has very few options on purpose, so every project formatted with it looks the same and code reviews skip arguments about style.

Why 88 characters per line?

Black's default is 88, a little longer than PEP 8's 79, because it found that gives shorter files with fewer awkward breaks. Pick 79 to follow PEP 8 exactly.

What does Sort imports do?

It runs isort first: imports are sorted alphabetically and grouped into the standard library, other packages and your own modules, the way Black users expect.

Is this a Python beautifier?

Yes: a beautifier, prettifier and formatter are the same idea. It also fixes indentation that mixes 2 and 4 spaces, as long as the code is valid Python.

Is my code sent to a server?

No. Black and isort run in your browser, with Python running on this page.