Pythonic Style & PEP 8
Pythonic Style & PEP 8
Section titled “Pythonic Style & PEP 8”Simple Analogy 🏠
Section titled “Simple Analogy 🏠”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.
The Zen of Python
Section titled “The Zen of Python”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.PEP 8 — Python’s Style Guide
Section titled “PEP 8 — Python’s Style Guide”Naming Conventions
Section titled “Naming Conventions”| What | Convention | Example |
|---|---|---|
| Variables / functions | snake_case | user_name, calculate_total() |
| Constants | UPPER_SNAKE_CASE | MAX_SIZE, DEFAULT_TIMEOUT |
| Classes | PascalCase | UserAccount, HttpClient |
| Private (by convention) | _leading_underscore | _internal_helper() |
| Dunder (magic methods) | __double_underscore__ | __init__, __str__ |
Code Layout
Section titled “Code Layout”# ✅ GOOD — Follows PEP 8
# Two blank lines between top-level definitionsdef function_one(): pass
def function_two(): pass
class MyClass: # One blank line between methods def method_one(self): pass
def method_two(self): passLine Length
Section titled “Line Length”# Keep lines under 79 characters for code, 72 for docstrings
# ✅ GOOD — break long linestotal = (price * quantity + tax - discount)
# ❌ BAD — too longtotal = price * quantity + tax - discount + shippingImports — Order Matters
Section titled “Imports — Order Matters”# ✅ GOOD — three groups, separated by blank lines# 1. Standard libraryimport osimport sysfrom datetime import datetime
# 2. Third-party packagesimport requestsimport pandas as pd
# 3. Local application modulesfrom mypackage import mymodulePythonic Idioms
Section titled “Pythonic Idioms”# Swap variables — no temp variable needed!a, b = b, a
# Check if a list is emptyif not items: # ✅ Pythonicif len(items) == 0: # ❌ Unnecessary
# Loop with indexfor i, item in enumerate(items): print(i, item)
# Combine conditionsif 0 < x < 10: # ✅ Pythonicif x > 0 and x < 10: # ❌ Overly verbose
# Default valuesdef greet(name="Guest"): # ✅ Pythonicdef greet(name=None): if name is None: name = "Guest" # ❌ Unnecessary
# File handlingwith open("file.txt") as f: # ✅ Pythonic — auto-closes content = f.read()
f = open("file.txt") # ❌ Must remember to closecontent = f.read()f.close()
# String joiningresult = ", ".join(items) # ✅ Pythonicresult = items[0] + ", " + items[1] # ❌ PainfulLinters and Formatters
Section titled “Linters and Formatters”| Tool | What It Does | Example |
|---|---|---|
| black | Auto-formats code (opinionated) | black myfile.py |
| ruff | Fast linter + formatter (replaces flake8, isort) | ruff check . |
| mypy | Static type checker | mypy myfile.py |
| pylint | Analyzes code for errors + style | pylint myfile.py |
# Installpip install black ruff mypy
# Format your code automaticallyblack myfile.py
# Check for issuesruff check myfile.py🧠 In Simple Words
Section titled “🧠 In Simple Words”- PEP 8 is Python’s official style guide — follow it so your code looks like everyone else’s
- Use
snake_casefor variables/functions,PascalCasefor classes - Keep lines under 79 characters, use meaningful names, organize imports properly
- Write Pythonic code — use idioms like
enumerate(),withstatements,if not list - Use linters (ruff, black) to automatically enforce style — no memorizing needed