The Evolution of a Bug Fix (Signal vs. Noise)

The problem: loading a JSON file in Python without leaking resources.

1. The Broken Code (4 Lines)

This code leaks a file handle, which will crash the program in a loop.

import json

def load_json(path):
    return json.load(open(path))  # <-- BUG: File handle is never closed.

2. The "Improved" Fix (40 Lines)

This fixes the bug, but buries the one-line fix under 39 lines of noise (imports, type hints, logging, docstrings, error handling, etc.). The fix is impossible to spot.

import json
import logging  # Noise
from typing import Any, Dict, Optional  # Noise

logger = logging.getLogger(__name__) # Noise

try:  # Noise (unrelated import)
    from transformers import AutoTokenizer
except Exception as e:
    logger.warning(f"Could not import: {e}")
    AutoTokenizer: Optional[Any] = None


def _load_json(path: str) -> Dict[str, Any]:
    """
    Safely load a JSON file... (20 lines of docstring noise)
    """
    import os # Noise
    
    if not os.path.exists(path):  # Noise (Pythonic to just try/except)
        raise FileNotFoundError(f"JSON file not found: {path}")
    
    try:
        with open(path, "r", encoding="utf-8") as f:  # <-- THE FIX
            data = json.load(f)
    except json.JSONDecodeError as e:  # Noise (over-handling)
        raise ValueError(f"Invalid JSON in {path}: {e}") from e
    except OSError as e:  # Noise (over-handling)
        raise OSError(f"Error reading file {path}: {e}") from e
    
    if not isinstance(data, dict):  # Noise (validation)
        raise ValueError(f"Expected dict in {path}, got {type(data).__name__}")
    
    return data

3. The Minimal Fix (5 Lines)

This is the correct, Pythonic way. It fixes the bug and adds zero noise. The signal is clear.

import json

def load_json(path):
    with open(path) as f:  # <-- THE FIX: Guarantees file closes.
        return json.load(f)

The Lesson: Strive for minimal code that solves the problem. The "overcomplicated" fix is 8x longer but no more correct. It just adds noise, which hides the signal and makes code harder to read and maintain.