Back to Blog

Python Best Practices - PEP8 Style Guide, Black, Ruff & Mypy Tutorial #41

Sandy LaneSandy Lane

Video: Python Best Practices - PEP8 Style Guide, Black, Ruff & Mypy Tutorial #41 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Python Best Practices: PEP8, Black, Ruff & Mypy Tutorial

This guide covers essential Python best practices including PEP8 naming conventions, automatic code formatting with Black, linting using Ruff, and static type checking with Mypy. You'll also learn how to write clear Google-style docstrings to produce clean, maintainable, and production-ready Python code.

Code

from typing import List

# Constants use UPPER_CASE
MAX_RETRIES = 5

# Function names and variables use snake_case
def fetch_data(url: str, retries: int = MAX_RETRIES) -> List[str]:
  """
  Fetch data from a URL with retry logic.

  Args:
    url (str): The URL to fetch data from.
    retries (int): Number of retry attempts.

  Returns:
    List[str]: List of lines fetched from the URL.
  """
  import requests

  for attempt in range(retries):
    response = requests.get(url)
    if response.status_code == 200:
      # Return list of lines
      return response.text.splitlines()
  # Raise error if all retries fail
  raise RuntimeError(f"Failed to fetch data from {url} after {retries} retries")

# Class names use PascalCase
class DataProcessor:
  def __init__(self, data: List[str]) -> None:
    self.data = data

  def process(self) -> List[str]:
    """Process data by stripping whitespace from each line."""
    return [line.strip() for line in self.data]

# Example usage
if __name__ == "__main__":
  url = "https://example.com/data.txt"
  data = fetch_data(url)
  processor = DataProcessor(data)
  cleaned_data = processor.process()
  print(cleaned_data)

Key Points

  • Follow PEP8 naming conventions: snake_case for functions/variables, PascalCase for classes, and UPPER_CASE for constants.
  • Use Black to automatically format your Python code for consistent style and readability.
  • Run Ruff as a linter to catch common errors and enforce style rules before committing code.
  • Leverage Mypy for static type checking to detect type-related bugs early in development.
  • Write clear, Google-style docstrings to document function arguments, return types, and behavior for maintainability.