Skip to content

PEP 8 (Python Enhancement Proposal 8) is the style guide for writing Python code. It helps you write code that is clean, readable, and consistent with the wider Python community.


โœ… PEP 8 โ€‹


๐Ÿ“ 1. Indentation โ€‹

  • Use 4 spaces per indentation level.
python
def my_function():
    x = 1
    if x > 0:
        print("Positive")

๐Ÿ”ด Avoid tabs or mixing tabs and spaces.


๐Ÿ“š 2. Maximum Line Length โ€‹

  • Keep lines โ‰ค 79 characters (for code)
  • Keep comments/docstrings โ‰ค 72 characters
python
# This is a comment that is short and sweet

For long expressions:

python
# OK - Implicit line continuation inside parentheses
total = (first_variable
         + second_variable
         + third_variable)

๐Ÿงพ 3. Blank Lines โ€‹

  • Top-level functions/classes: 2 blank lines
  • Methods inside a class: 1 blank line
python
class MyClass:
    
    def method_one(self):
        pass

    def method_two(self):
        pass

๐Ÿ”ค 4. Imports โ€‹

  • Import standard libraries, third-party libraries, and local imports in separate sections with blank lines in between.
  • Always import each module on a separate line
python
# Correct
import os
import sys

# Wrong
import sys, os

Ordering:

python
import os
import sys

import requests

import my_local_module

๐Ÿง  5. Naming Conventions โ€‹

TypeConventionExample
Variablelower_case_with_underscorestotal_count
Functionlower_case_with_underscorescalculate_sum()
ClassCapitalizedWordsMyClass
ConstantsALL_CAPSMAX_RETRIES
Modulesshort_lowercaseutils.py
Private_single_leading_underscore_internal
Special__double_underscores____init__

โ“ 6. Use of Whitespace โ€‹

๐Ÿ‘ Correct: โ€‹

python
x = 1
y = 2
z = x + y

๐Ÿ‘Ž Wrong: โ€‹

python
x=1
y =2
z= x+y

More guidelines: โ€‹

  • No space before a comma, semicolon, colon:

    python
    print(x, y)
  • Yes space after:

    python
    print(x, y)
  • No space inside brackets:

    python
    my_list = [1, 2, 3]

๐Ÿงพ 7. Comments โ€‹

Inline comments: โ€‹

python
x = x + 1  # Increment x

Block comments: โ€‹

python
# This function adds two numbers
# and returns the result
def add(x, y):
    return x + y

Docstrings (triple quotes): โ€‹

python
def add(x, y):
    """Add two numbers and return the result."""
    return x + y

โœ… 8. Comparison to None and Booleans โ€‹

  • Use is / is not with None, not == or !=:
python
if x is None:
    ...
  • Avoid comparisons to True or False:
python
# Good
if is_valid:
    ...

# Bad
if is_valid == True:
    ...

๐Ÿงผ 9. Avoid Unnecessary Expressions โ€‹

python
# Good
if not x:
    ...

# Bad
if x == False:
    ...

๐Ÿงฐ 10. Function and Class Definitions โ€‹

Leave 2 blank lines before top-level functions and classes.

python
def my_function():
    ...

class MyClass:
    ...

๐Ÿงน 11. Using linters โ€‹

Tools like flake8, pylint, or black automatically check or format code according to PEP 8.

black auto-formats your code:

bash
pip install black

๐Ÿงฉ 12. Continuation Line Indentation โ€‹

Use 4 spaces for wrapped lines, aligning naturally or with parentheses:

python
# Align with open delimiter
my_function(param_one, param_two,
            param_three, param_four)

# Or aligned with first argument
my_function(
    param_one, param_two,
    param_three
)

๐Ÿงฎ 13. Avoid Lambda for Complex Logic โ€‹

python
# OK
squares = map(lambda x: x*x, numbers)

# Better for readability
def square(x): return x*x
squares = map(square, numbers)

โŒ 14. Don't Use Wildcard Imports โ€‹

python
# Bad
from math import *

# Good
from math import sqrt, pi

โš™๏ธ 15. Consistent Exception Handling โ€‹

python
try:
    ...
except ValueError as e:
    print(e)

๐Ÿ“ฆ 16. Avoid Mutable Defaults โ€‹

python
# Bad
def add_item(item, my_list=[]):
    my_list.append(item)
    return my_list

# Good
def add_item(item, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(item)
    return my_list

๐Ÿง‘โ€๐Ÿ’ป Summary โ€‹

ConceptRule/Best Practice
Indentation4 spaces
Line lengthโ‰ค 79 characters
ImportsGrouped: stdlib, 3rd-party, local
NamingUse snake_case, PascalCase, UPPER_CASE
CommentsUse inline & block, write meaningful
WhitespaceBe consistent, avoid extra spaces
DocstringsUse triple quotes for functions/classes
ToolsUse black, flake8, isort, etc.

<<>> with โ™ฅ๏ธ by S@Nchit