🌱 Junior Track 26 of 27

26. Debugging & Troubleshooting

Diagnose bugs efficiently by reading Python tracebacks, inspecting execution with `breakpoint()` and `pdb`, transitioning from `print()` to structured `logging`, and inspecting deep stack frames with `traceback.format_exc()`.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 26 — DEBUGGING & TROUBLESHOOTING
# ==============================================================================
import logging
import sys
import traceback

# 1. Structured Logging Configuration (Replacing print() statements)
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    datefmt="%H:%M:%S"
)
logger = logging.getLogger("TransactionProcessor")


# 2. Buggy Function for Traceback & Debugger Demonstration
def calculate_discount(price: float, discount_percent: float) -> float:
    logger.debug(f"Calculating discount for price={price}, discount={discount_percent}%")
    
    if discount_percent < 0 or discount_percent > 100:
        logger.error(f"Invalid discount percent: {discount_percent}")
        raise ValueError("Discount percentage must be between 0 and 100")
    
    discount_amount = price * (discount_percent / 100)
    final_price = price - discount_amount
    
    logger.info(f"Final calculated price: ${final_price:.2f}")
    return final_price


# 3. Stack Trace Inspection with traceback module
def process_order(order_id: str, item_price: float, discount: float):
    try:
        logger.info(f"Processing Order #{order_id}")
        result = calculate_discount(item_price, discount)
        return result
    except ValueError as err:
        logger.warning(f"Handled error in order processing: {err}")
        # Extract stack trace as string without crashing
        stack_trace_str = traceback.format_exc()
        print("\n--- CAPTURED STACK TRACE ---")
        print(stack_trace_str)
        return None


# 4. Interactive Breakpoint Inspection (Python 3.7+ breakpoint())
def debug_demo_mode():
    total_val = 150.0
    tax_rate = 0.08
    grand_total = total_val * (1 + tax_rate)
    
    # In interactive terminals, breakpoint() invokes pdb:
    # breakpoint()  # Commands: (Pdb) p total_val -> 150.0, c -> continue
    return grand_total


if __name__ == "__main__":
    print("=== 1. Valid Calculation ===")
    process_order("ORD-101", 200.0, 15.0)

    print("\n=== 2. Invalid Input & Traceback Capture ===")
    process_order("ORD-102", 200.0, 150.0)

    print("\n=== 3. Debugger Demo ===")
    res = debug_demo_mode()
    print(f"Grand Total: ${res:.2f}")
🌱 Junior Track 26 Master Reference

26. Debugging, PDB, Logging & Tracebacks Guide

🐞 Python Debugger (PDB) Essential Commands

Command Shortcut Description
print / p p var_name Prints the value of an expression or variable in the current frame.
next n Executes the current line and steps over to the next line in the current function.
step s Steps inside the function call on the current line.
continue c Resumes program execution until the next breakpoint or completion.
where / bt w Displays a stack trace of all active frames leading to the current line.

📜 Logging Levels & Severity Matrix

Level Numeric Value When to Use
DEBUG 10 Detailed diagnostic information for developers during problem diagnosis.
INFO 20 Confirmation that operational workflows (requests, jobs) completed as expected.
WARNING 30 Indicates unexpected conditions or potential problems (e.g. low disk space).
ERROR 40 Serious error; software failed to execute a specific operation or request.
CRITICAL 50 Fatal failure; application or server process cannot continue running.

⭐ Rate Track 26: Debugging with pdb & Breakpoints (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 25. Testing & Pytest 🌱 Junior Hub (27 Modules Complete!) 27. Logging & Diagnostics →