Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Escape HTML in Python
This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.
import html
def escape_user_input(user_input: str) -> str:
"""Escape HTML-sensitive characters for safe display."""
return html.escape(user_input)
if __name__ == "__main__":
sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
safe_output = escape_user_input(sample_user_input)
print("…
How to Use Keyword-Only Arguments in Python Functions
Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.
def greet(name, *, greeting="Hello", punctuation="!"):
"""Greet someone with a customizable message using keyword-only arguments."""
message = f"{greeting}, {name}{punctuation}"
return message
if __name__ == "__main__":
# Basic call with only the positional argument
print(greet("Alice"))
# Al…
How to Load Pickle Files Safely in Python
This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.
import pickle
# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
def __reduce__(self):
return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))
# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())
# Safe ap…
How to Write a List of Lines to a Text File Safely in Python
This code atomically writes a list of strings as lines to a text file using a temporary file and os.replace to prevent corruption.
from pathlib import Path
import tempfile
import os
def write_lines_safely(lines: list[str], filepath: str | Path) -> None:
"""Write lines to a text file atomically to avoid corruption."""
path = Path(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(dir=str…
Parameterize SQL queries in Python to prevent SQL injection
Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.
import sqlite3
def get_users_by_name(name):
"""Fetch users safely using parameterized query."""
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
# Create sample table and data
cursor.execute('CREATE TABLE users (id INTEGER, name TEXT)')
cursor.executemany('INSERT INTO users (name…
How to Invert a Dictionary in Python Safely
Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.
def invert_dict_safely(d):
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = key
else:
raise ValueError(f"Duplicate value '{value}' would cause data loss")
return inverted
if __name__ == "__main__":
sample = {"a": 1, "b": 2,…
How to Create Immutable Data Classes with frozen=True in Python
Create immutable data classes in Python using @dataclass(frozen=True) to prevent attribute modifications after instantiation.
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
def distance_from_origin(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
if __name__ == "__main__":
p = Point(3.0, 4.0)
print(p)
print(f"Distance from origin: {p.distance_from_origin():.2f}…
How to Use __slots__ in Python Classes for Memory Efficiency
Defines classes with __slots__ to prevent dynamic attribute creation and reduce memory usage, including inheritance with additional slots.
```python
class Person:
__slots__ = ("name", "age")
def __init__(self, name: str, age: int):
self.name = name
self.age = age
def greet(self) -> str:
return f"Hi, I'm {self.name} and I'm {self.age} years old."
class Employee(Person):
__slots__ = ("role",)
def __init__(se…
Observer Pattern in Python: Notify Listeners
Implement the Observer design pattern in Python with a Subject class that manages listeners and notifies them with messages.
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(me…
Slots Class: How to Reduce Memory Usage in Python
Use __slots__ to prevent dynamic attribute creation and reduce per-instance memory overhead, while keeping methods intact.
class SlotsDemo:
__slots__ = ("name", "age", "email")
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
def describe(self):
return f"{self.name}, {self.age}, {self.email}"
if __name__ == "__main__":
instance = SlotsDemo("Alice", …
Build a Live Countdown Timer for Events in Python
A Python script that displays a real-time countdown to a target date and time, updating every second in the console.
import datetime
import time
def countdown(event_name, target_datetime):
"""Displays a live countdown to a target datetime."""
while True:
now = datetime.datetime.now()
remaining = target_datetime - now
if remaining.total_seconds() <= 0:
print(f"\n🚀 {event_name} is happening…
Generate a Monthly Report CSV from Log Files in Python
Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.
import csv
from collections import defaultdict
from datetime import datetime
def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
events_by_date = defaultdict(int)
revenue_by_date = defaultdict(float)
with open(log_file, 'r') as f:
for line in f:
date_…
Track Internet Connectivity and Downtime Automatically in Python
Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.
import time
import subprocess
from datetime import datetime
def check_internet(host="8.8.8.8", timeout=3):
"""Returns True if internet is reachable via ping."""
try:
subprocess.run(
["ping", "-c", "1", "-W", str(timeout), host],
capture_output=True,
timeout=timeout …
Deduplicate events by ID within a window in Python
Deduplicate event streams by ID within sliding time windows, keeping the newest occurrence per window using heaps and sets.
import heapq
from collections import defaultdict
def deduplicate_events(events, window_size):
"""Return events deduplicated by id, keeping newest within each sliding window."""
# Index events by (timestamp, id) for deterministic ordering
events_by_id = defaultdict(list)
for ts, eid, *payload in events…
Enrich Events with Geo IP Data in Python
Returns a copy of each event dictionary, enriched with a geo-location dict from a mock IP-to-geo lookup table, with a fallback for unknown IPs.
import ipaddress
GEO_IP_DB = {
"192.168.1.10": {"country": "US", "city": "New York", "lat": 40.7128, "lon": -74.0060},
"10.0.0.5": {"country": "DE", "city": "Berlin", "lat": 52.5200, "lon": 13.4050},
"172.16.0.8": {"country": "JP", "city": "Tokyo", "lat": 35.6762, "lon": 139.6503},
}
EVENTS = [
{"id…
Group Python Events into Sessions with a Gap Timeout
Groups timestamped events into sessions, starting a new session when the time gap exceeds a specified timeout.
from itertools import groupby
from datetime import datetime, timedelta
def session_window_group(events, gap_seconds=300):
"""Group events into sessions where gap > gap_seconds starts a new session."""
if not events:
return []
events = sorted(events, key=lambda x: x[0])
sessions = []
c…
How to Count Events by Minute with a Tumbling Window in Python
Group timestamps into fixed 60-second tumbling windows and count events per bucket using a dict.
from collections import defaultdict
from datetime import datetime, timedelta
def tumbling_window_count(events, window_seconds=60):
buckets = defaultdict(int)
for event in events:
ts = datetime.fromisoformat(event["timestamp"])
bucket_start = ts - timedelta(seconds=ts.second % window_seconds,
…
How to Deduplicate Events with At-Least-Once Delivery in Python
Implements an exactly-once processing pattern for at-least-once event delivery by tracking seen event IDs in a set, skipping duplicates.
seen_ids = set()
def process_event(event_id: str, payload: dict) -> dict:
"""Process an event exactly once, ignoring duplicates."""
if event_id in seen_ids:
return {"status": "duplicate", "event_id": event_id}
seen_ids.add(event_id)
return {"status": "processed", "event_id": event_id, **payloa…
How to route late-arriving data to a side output in Python
Separate late-arriving events from a streaming data batch into a dead-letter side output list using a timestamp threshold.
from collections import defaultdict
def late_arriving_side_output(events, late_threshold_ts):
"""
Mock a streaming pipeline that separates late-arriving data events
into a side output list (e.g., for dead-letter analysis).
events: list of (timestamp, data) tuples, timestamps as ints.
late_thresho…
Generate Mock CloudFormation Stack Events in Python
Generate a list of mock AWS CloudFormation stack events with random resources, statuses, and timestamps, and print them as JSON.
import json
import random
from datetime import datetime, timedelta
def generate_mock_stack_events(stack_name="MyTestStack", num_events=10):
"""Generate a list of mock CloudFormation stack events."""
resources = [
("AWS::S3::Bucket", "MyBucket"),
("AWS::EC2::Instance", "MyInstance"),
("…
How to Mock Auto Scaling Policy Scale Out in Python
Define a mock auto-scaling function that scales out capacity by a factor up to a max, simulating AWS-like events.
def mock_scale_out(current_capacity: int, max_capacity: int, scale_factor: int = 1) -> tuple:
"""
Mock auto-scaling policy: scales out by the specified factor
if capacity allows, capped at max_capacity.
"""
if current_capacity >= max_capacity:
return current_capacity, False
new_cap…
How to Mock GCP Cloud Functions HTTP Events in Python
Simulate a GCP Cloud Functions HTTP event with a Python mock handler that constructs a realistic event payload and returns a JSON response.
import json
from datetime import datetime, timezone
def mock_http_event(data):
"""Simulate a GCP Cloud Function HTTP event."""
event = {
"event_id": "mock-event-12345",
"timestamp": datetime.now(timezone.utc).isoformat(),
"event_type": "google.cloud.functions.http",
"resource"…
How to Parse an AWS API Gateway Proxy Event in Python
Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.
import json
from typing import Any, Dict, Optional
def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
"""Extract and parse common fields from an API Gateway proxy event."""
body = event.get("body", "")
if isinstance(body, str):
body = json.loads(body) if body else {}
elif body is…
Mock Lambda handler event context dict in Python
Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.
import json
def lambda_handler(event, context):
"""
A mock AWS Lambda handler that processes an event dict and context object.
Demonstrates the typical Lambda function signature and basic event/context usage.
"""
print("Received event:", json.dumps(event, indent=2))
print("Function name:", co…
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.