Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
How to Debug Print Behind a DEBUG Environment Flag in Python
Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.
import os
def debug_print(*args, **kwargs):
"""Print only when DEBUG environment variable is set to a truthy value."""
if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
print(*args, **kwargs)
if __name__ == "__main__":
# Example usage: run as `DEBUG=1 python script.py` to se…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
Use pprint for Nested Structure Debug Output in Python
Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.
from pprint import pprint
def build_nested_structure():
"""Create a sample nested data structure for demonstration."""
return {
"project": "DataPipeline",
"config": {
"inputs": ["raw_1.json", "raw_2.json"],
"processing": {
"steps": ["clean", "transform",…
Browse by section
Each section groups closely related Python snippets.
Errors & debugging — Python code examples
What you will find here
This page collects errors & debugging snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.