4.16 Coding Standards (PEP 8)
PEP 8 from the syntax angle — indentation, line length, naming conventions, import ordering, and whitespace rules that affect how Python code is laid out.
PEP 8 is Python’s official style guide. This section covers it from the syntax angle — the specific formatting rules that affect how code is laid out on the page.
Indentation
4 spaces per indentation level; never mix tabs and spaces (mixing raises a TabError in Python 3).
Line Length
Limit lines to 79 characters (or up to 99 by some team conventions) — keeps code readable side-by-side in diffs and split editor panes.
Naming
snake_case for variables/functions, PascalCase for classes, UPPER_SNAKE_CASE for constants — the same table introduced in Introduction to Python.
Imports
One import per line, grouped in order: standard library, then third-party packages, then local application imports — with a blank line between each group.
import os
import sys
import boto3
from myapp.utils import helper
Whitespace
Use a single space around operators and after commas; avoid extra spaces right inside brackets or right before a function call’s parentheses.
# PEP 8 compliant
total = price * quantity
func(a, b, c)
# Not PEP 8 compliant
total = price*quantity
func( a,b,c )
Quick Interview Answer
“PEP 8 is Python’s official style guide — 4-space indentation, a 79-character line limit,
snake_case/PascalCase/UPPER_SNAKE_CASEnaming by identifier type, imports grouped stdlib → third-party → local with one per line, and consistent spacing around operators. Tools likeblackorflake8enforce most of it automatically, so it’s rarely a manual judgment call on a real team.”
Common Mistakes
- Mixing import groups together instead of ordering standard library, then third-party, then local application imports.
- Inconsistent spacing around operators (
price*quantityvsprice * quantity) that a formatter likeblackwould catch automatically. - Treating PEP 8 as optional style preference rather than the shared convention that keeps a team’s codebase consistently readable.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form