Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

52 matches
Strings & text easy

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.

html escaping security
Python
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("…
13 0 Open
Functions & basics easy

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.

functions keyword-arguments function-signature
Python
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…
15 0 Open
Files & data easy

Parameterize SQL queries in Python to prevent SQL injection

Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.

sqlite3 sql injection parameterized query
Python
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…
15 0 Open
Dictionaries & sets easy

How to Invert a Dictionary in Python Safely

Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.

dictionary inversion data-safety
Python
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,…
15 0 Open
OOP & classes easy

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.

dataclass frozen immutable
Python
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}…
13 0 Open
OOP & classes easy

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.

memory slots class
Python
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", …
12 0 Open
Automation & scripting easy

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.

datetime countdown timers
Python
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…
45 0 Open
Automation & scripting easy

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.

csv logs report
Python
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_…
14 0 Open
Data pipelines & processing easy

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.

data-enrichment dictionaries pipelines
Python
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…
14 0 Open
Data pipelines & processing easy

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.

sessions grouping datetime
Python
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…
13 0 Open
Data pipelines & processing easy

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.

deduplication idempotent event-processing
Python
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…
13 0 Open
Data pipelines & processing easy

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.

data pipelines streaming dead-letter
Python
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…
12 0 Open
Cloud + Python easy

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.

cloudformation mock aws
Python
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"),
        ("…
15 0 Open
Cloud + Python easy

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.

auto-scaling cloud simulation
Python
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…
14 0 Open
Cloud + Python easy

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.

gcp cloud-functions mock
Python
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"…
13 0 Open
Cloud + Python easy

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.

aws lambda api-gateway
Python
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…
13 0 Open
Cloud + Python easy

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.

lambda aws mock
Python
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…
14 0 Open
Modern tooling easy

How to Initialize Sentry SDK with a Mock DSN in Python

Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.

sentry sdk dsn
Python
import sentry_sdk

# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
    dsn="https://mock-public@mock-host/mock-project",
    traces_sample_rate=1.0,
    environment="development",
)

# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
13 0 Open
Concurrency & performance easy

How to Run an Async Main with asyncio.run in Python

Show the canonical entry point for an asyncio program: define an async main, then launch it with asyncio.run.

asyncio event loop entry point
Python
import asyncio


async def main():
    print("Hello from async main")
    await asyncio.sleep(0.1)
    print("Done")


if __name__ == "__main__":
    asyncio.run(main())
16 0 Open
Concurrency & performance easy

How to Signal asyncio Workers to Stop with an Event in Python

Use an asyncio.Event to coordinate graceful shutdown of multiple concurrent worker tasks in Python.

asyncio events concurrency
Python
import asyncio
import random

async def worker(name, stop_event):
    while not stop_event.is_set():
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Worker {name} processing...")
    print(f"Worker {name} stopped.")

async def main():
    stop_event = asyncio.Event()
    workers = [asyncio.create…
11 0 Open
Concurrency & performance easy

How to Use threading.Lock to Synchronize a Counter in Python

Safely increment a shared counter across multiple threads using threading.Lock as a mutex to prevent race conditions.

threading lock mutex
Python
import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Final counter valu…
14 0 Open
Concurrency & performance easy

How to Use uvloop Faster Event Loop

Install uvloop at startup to replace asyncio's default event loop with a faster libuv-based one, with a graceful fallback when it's unavailable.

uvloop asyncio event-loop
Python
import asyncio
try:
    import uvloop
    uvloop.install()
    USING_UVLOOP = True
except ImportError:
    USING_UVLOOP = False


async def fetch_data(index):
    await asyncio.sleep(0.01)
    return f"data-{index}"


async def main():
    tasks = [fetch_data(i) for i in range(10)]
    results = await asyncio.gather(*…
14 0 Open
Concurrency & performance easy

How to set a timeout with asyncio.wait_for in Python

Use asyncio.wait_for to bound an async function with a timeout, catching TimeoutError when it exceeds the limit.

asyncio timeout concurrency
Python
import asyncio

async def slow_task():
    await asyncio.sleep(3)
    return "finished"

async def main():
    try:
        result = await asyncio.wait_for(slow_task(), timeout=1)
        print(result)
    except asyncio.TimeoutError:
        print("Task timed out")

if __name__ == "__main__":
    asyncio.run(main())
13 0 Open
Concurrency & performance easy

Run Background Tasks with asyncio.create_task in Python

Create background tasks in an asyncio event loop with asyncio.create_task and run them concurrently using asyncio.gather.

asyncio async concurrency
Python
import asyncio
import time

async def background_worker(name, duration):
    """Simulates a long-running background task."""
    print(f"{name} started at t={time.monotonic():.1f}")
    await asyncio.sleep(duration)
    print(f"{name} finished at t={time.monotonic():.1f}")

async def main():
    print(f"Main starting …
13 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.