Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Redact Secrets from Log Messages in Python
Build a lightweight RedactingFormatter class that replaces sensitive tokens like passwords and API keys with [REDACTED] before log messages are printed.
class RedactingFormatter:
def __init__(self, secrets):
self.secrets = secrets
def redact(self, message):
for secret in self.secrets:
message = message.replace(secret, "[REDACTED]")
return message
def format(self, record):
message = record["message"]
ret…
How to Ship Logs to an Aggregator Endpoint in Python
Ship batched log entries to a mock HTTP aggregator endpoint with proper error handling and response status.
import json
import requests
from datetime import datetime, timezone
LOG_ENTRIES = [
{"timestamp": "2024-01-15T10:00:00Z", "level": "INFO", "message": "Server started"},
{"timestamp": "2024-01-15T10:00:05Z", "level": "WARN", "message": "High memory usage"},
{"timestamp": "2024-01-15T10:00:10Z", "level": "E…
How to Use Log Levels DEBUG INFO WARNING ERROR in Python
Demonstrates Python's logging levels (DEBUG, INFO, WARNING, ERROR) with basicConfig and a logger, showing how severity filtering controls output.
import logging
# Configure a mock logger to demonstrate log levels
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
logger = logging.getLogger("mock_logger")
# Simulate events at each severity level
logger.debug("Detailed diagnostic info")
logger.info("General system operation")
logger.w…
Python Observability Data Helper for Beginners
A beginner-friendly Python helper to log events, record metrics, summarize observability data, and export it as JSON.
import json
from datetime import datetime
from collections import defaultdict
class ObservabilityDataHelper:
"""Helper for exploring basic observability data patterns."""
def __init__(self):
self.events = []
self.metrics = defaultdict(list)
def log_event(self, service, level, message):
…
Mock a Sidecar Logger with Python Metrics
Simulate a sidecar logger that tracks request counts, error rates, and endpoint hits, producing a metrics snapshot.
import random
import time
from collections import defaultdict
class SidecarLogger:
def __init__(self):
self.metrics = defaultdict(int)
self.total_requests = 0
self.error_count = 0
def log_request(self, endpoint, status_code):
"""Simulate logging a request and updating metrics…
How to Mock a User-Defined Function (UDF) in Python
Wrap a real UDF implementation with call logging to simulate and track invocations in a data pipeline.
from typing import Any, Callable
# Mock a user-defined function (UDF) that was previously complex or external
def mock_udf(name: str, implementation: Callable[..., Any], *, calls: list[Any]) -> Callable[..., Any]:
"""Wrap a real implementation with call logging to simulate a UDF."""
def wrapper(*args: Any, *…
How to Mock MLflow log_params and log_metrics in Python
Use unittest.mock to patch MLflow's log_param and log_metric, run the training function, and verify logging calls without touching a real tracking server.
from unittest.mock import Mock, patch
import mlflow
def train_model():
mlflow.log_param("learning_rate", 0.01)
mlflow.log_param("epochs", 10)
mlflow.log_metric("accuracy", 0.95)
mlflow.log_metric("loss", 0.05)
return "Training completed"
if __name__ == "__main__":
with patch("mlflow.log_par…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.