Loading ...

📚 Chapters

PEP8 – Python Coding Standard and Best Practices

✍️ By Arun Kumar | 11/14/2025

PEP 8 stands for Python Enhancement Proposal 8 — it is the official style guide for writing Python code. Following PEP 8 makes your Python code consistent, readable, and maintainable, especially when working in teams.

Here’s a detailed breakdown:


1. Indentation

  • Use 4 spaces per indentation level (not tabs).

# Bad def add(a,b): return a+b # Good def add(a, b): return a + b

2. Line Length

  • Limit lines to 79 characters (for code) and 72 for docstrings/comments.

# Bad print("This is a very long line that exceeds the recommended 79 characters limit in PEP8") # Good print( "This is a line wrapped properly according to PEP8 recommendations" )

3. Blank Lines

  • Top-level functions/classes: 2 blank lines before

  • Methods inside a class: 1 blank line before

class MyClass: def method1(self): pass def method2(self): pass def top_level_function(): pass

4. Imports

  • Imports should usually be on separate lines and ordered:

1. Standard library 2. Third-party libraries 3. Local application imports
# Bad import sys, os, requests # Good import os import sys import requests from mymodule import myfunction

5. Spaces in Expressions

  • Avoid extra spaces:

# Bad x = 1 + 2 y = 3* 4 z = ( 5 + 6 ) # Good x = 1 + 2 y = 3 * 4 z = (5 + 6)

6. Naming Conventions

TypeStyleExample
Variable / functionsnake_casetotal_sum, get_user_input
ConstantUPPER_CASEPI = 3.14
ClassPascalCaseUserAccount
Module / Packagesnake_caseutils.py, data_processing

7. String Quotes

  • Either single ' or double " quotes are fine, be consistent.

# Bad string1 = "Hello" string2 = 'World' # Good string1 = "Hello" string2 = "World"

8. Function Annotations (Optional but Recommended)

  • Include type hints for clarity:

def greet(name: str) -> str: return f"Hello, {name}"

9. Comments

  • Use complete sentences, capitalize first letter, avoid obvious comments.

# Bad x = x + 1 # increment x # Good # Adjust index to match 1-based numbering index += 1

10. Example Putting It All Together

import os import sys from mymodule import calculate_sum PI = 3.14159 # Constant class Circle: def __init__(self, radius: float): self.radius = radius def area(self) -> float: """Calculate area of the circle.""" return PI * self.radius ** 2 def main(): circle = Circle(5) print(f"Area: {circle.area()}") if __name__ == "__main__": main()

Summary

-------------

PEP 8 ensures your code is:

  • Readable → others (and future you) can understand it

  • Consistent → same rules across projects and teams

  • Maintainable → easier to debug, refactor, and extend

💬 Comments

logo

Comments (0)

No comments yet. Be the first to share your thoughts!