PEP 8

A beginner-friendly guide to PEP 8, the official Python style guide for writing clean and readable code.

Loading...
PEP 8

What is PEP 8?

PEP 8 is a style guide for writing Python code. It outlines conventions and best practices that ensure:

  1. Consistency: Code looks uniform, making it easier to read and understand.
  2. Readability: It emphasizes writing clean and readable code.
  3. Community Standards: Encourages practices accepted and expected by the Python community.

Purpose of PEP 8

  • Help Python developers write more understandable code.
  • Ensure consistent style across Python codebases.
  • Make it easier for newcomers to read and contribute to existing Python projects.

Key PEP 8 Guidelines

  1. Indentation:

    • Use 4 spaces per indentation level.
    • Never mix tabs and spaces.
    def example_function():
        for i in range(10):
            print(i)  # 4 spaces used for indentation
     
  2. Line Length:

    • Limit lines to a maximum of 79 characters.
    • For longer blocks of text (like comments), limit them to 72 characters.
    # This is a very long comment. To improve readability, limit lines
    # to 72 characters when writing block comments like this.
     
  3. Blank Lines:

    • Use blank lines to separate functions, classes, and blocks of code.
    class Example:
        def method_one(self):
            pass
     
        def method_two(self):
            pass
     
  4. Imports:

    • Place all imports at the top of the file.
    • Group imports in the following order:
      1. Standard library imports.
      2. Third-party library imports.
      3. Local application/library-specific imports.
    # Example:
    import os
    import sys
     
    import numpy as np
     
    from myproject import mymodule
     
  5. Whitespace:

    • Avoid extra spaces in expressions or statements.
    # Correct:
    x = 1 + 2
    y = (a, b)
     
    # Incorrect:
    x = 1  + 2
    y = ( a, b )
     
    # Also incorrect:
    x    = 1 + 2
     
     
  6. Naming Conventions:

    • Variable and function names: snake_case
    • Class names: PascalCase
    • Constants: UPPER_CASE
    # Example:
    class MyClass:
        def my_method(self):
            my_variable = 42
     
  7. Comments:

    • Comments should be concise and relevant.
    • Use complete sentences when explaining complex code.
    # Correct:
    # This function calculates the square of a number.
    def square(n):
        return n ** 2
     
    # Incorrect:
    # function calc square
    def square(n):
        return n ** 2
     
  8. Docstrings:

    • Use triple quotes for docstrings, and include a description for classes, functions, and modules.
    def add(a, b):
        """Return the sum of a and b."""
        return a + b
     

👉 Next tutorial: The Zen of Python

Support Learnify!