Skip to content

Pythonic Style & PEP 8

Think of writing code like organizing a kitchen. If every chef follows the same rules (knives here, spices there, pots below), anyone can walk in and cook. PEP 8 is the rulebook for making Python code consistent and readable across the entire community.


Type import this in a Python REPL. It reveals the guiding principles:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Flat is better than nested.
Readability counts.

WhatConventionExample
Variables / functionssnake_caseuser_name, calculate_total()
ConstantsUPPER_SNAKE_CASEMAX_SIZE, DEFAULT_TIMEOUT
ClassesPascalCaseUserAccount, HttpClient
Private (by convention)_leading_underscore_internal_helper()
Dunder (magic methods)__double_underscore____init__, __str__
# ✅ GOOD — Follows PEP 8
# Two blank lines between top-level definitions
def function_one():
pass
def function_two():
pass
class MyClass:
# One blank line between methods
def method_one(self):
pass
def method_two(self):
pass
# Keep lines under 79 characters for code, 72 for docstrings
# ✅ GOOD — break long lines
total = (price * quantity
+ tax
- discount)
# ❌ BAD — too long
total = price * quantity + tax - discount + shipping
# ✅ GOOD — three groups, separated by blank lines
# 1. Standard library
import os
import sys
from datetime import datetime
# 2. Third-party packages
import requests
import pandas as pd
# 3. Local application modules
from mypackage import mymodule

# Swap variables — no temp variable needed!
a, b = b, a
# Check if a list is empty
if not items: # ✅ Pythonic
if len(items) == 0: # ❌ Unnecessary
# Loop with index
for i, item in enumerate(items):
print(i, item)
# Combine conditions
if 0 < x < 10: # ✅ Pythonic
if x > 0 and x < 10: # ❌ Overly verbose
# Default values
def greet(name="Guest"): # ✅ Pythonic
def greet(name=None):
if name is None:
name = "Guest" # ❌ Unnecessary
# File handling
with open("file.txt") as f: # ✅ Pythonic — auto-closes
content = f.read()
f = open("file.txt") # ❌ Must remember to close
content = f.read()
f.close()
# String joining
result = ", ".join(items) # ✅ Pythonic
result = items[0] + ", " + items[1] # ❌ Painful

ToolWhat It DoesExample
blackAuto-formats code (opinionated)black myfile.py
ruffFast linter + formatter (replaces flake8, isort)ruff check .
mypyStatic type checkermypy myfile.py
pylintAnalyzes code for errors + stylepylint myfile.py
Terminal window
# Install
pip install black ruff mypy
# Format your code automatically
black myfile.py
# Check for issues
ruff check myfile.py

  • PEP 8 is Python’s official style guide — follow it so your code looks like everyone else’s
  • Use snake_case for variables/functions, PascalCase for classes
  • Keep lines under 79 characters, use meaningful names, organize imports properly
  • Write Pythonic code — use idioms like enumerate(), with statements, if not list
  • Use linters (ruff, black) to automatically enforce style — no memorizing needed