Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

60 matches
Files & data easy

Create an In-Memory SQLite Table and Query It in Python

This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.

sqlite in-memory database
Python
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT NOT NULL,
        salary REAL
    )
""")

employees = [
    (1, "Alice", "Engineering", 95000),
    (2, "Bob", "…
11 0 Open
Files & data easy

Export SQLite Query Results to CSV in Python

Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.

sqlite csv export
Python
import sqlite3
import csv

def export_query_to_csv(db_path, query, csv_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(query)

    rows = cursor.fetchall()
    column_names = [description[0] for description in cursor.description]

    with open(csv_path, 'w', newline='', encodi…
17 0 Open
Files & data easy

How to Bulk Insert Rows into SQLite in Python

Insert many rows into an SQLite table in one call with cursor.executemany, then verify them with a SELECT query.

sqlite bulk-insert database
Python
import sqlite3

# Create an in-memory database and a table
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE products (name TEXT, price REAL, quantity INTEGER)")

# Data to insert in bulk
products = [
    ("Laptop", 999.99, 5),
    ("Mouse", 19.99, 50),
    ("Keyboard", 49.99, 30),…
13 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
Files & data easy

Read SQLite database with sqlite3 module in Python

Connect to a SQLite database and query rows with the standard library sqlite3 module, returning results as dictionaries.

sqlite database stdlib
Python
import sqlite3
from pathlib import Path

# Create an in-memory database and a sample table
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()

cursor.execute("""
CREATE TABLE employees (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    department TEXT NOT NULL,
    salary REAL
)
""")

# Inser…
17 0 Open
Comprehensions & generators easy

Batch Rows in Chunks with a Generator in Python

Group a list of row dicts into fixed-size chunks using a generator that yields one slice per call.

generators chunking database
Python
from typing import Iterator, List


def batch_rows(rows: List[dict], batch_size: int) -> Iterator[List[dict]]:
    for i in range(0, len(rows), batch_size):
        yield rows[i:i + batch_size]


if __name__ == "__main__":
    sample_rows = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"},
      …
15 0 Open
Automation & scripting easy

How to Backup an SQLite Database with a Timestamp in Python

Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.

sqlite backup automation
Python
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path

def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
    db = Path(db_path)
    backup_folder = Path(backup_dir)
    backup_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 …
14 0 Open
Automation & scripting easy

Restore sqlite from latest backup file in Python

This script finds the most recently modified backup file in a directory and restores it to the main database path, then verifies the restored data.

sqlite backup file-io
Python
import sqlite3
import glob
import os
import shutil

def restore_latest_backup(db_path, backup_dir):
    backups = sorted(glob.glob(os.path.join(backup_dir, "*.db")), key=os.path.getmtime)
    if not backups:
        raise FileNotFoundError("No backup files found")
    latest = backups[-1]
    shutil.copy2(latest, db_p…
14 0 Open
Data pipelines & processing easy

Fan Out Records to Multiple Sinks in Python

Distribute the same records across multiple target sinks (database, API, queue, etc.) using a defaultdict-based fan-out pattern.

fan-out defaultdict records
Python
import json
from collections import defaultdict

SINKS = ["database", "api", "message_queue", "data_lake", "monitoring"]

def fan_out(records, *sinks):
    dist = defaultdict(list)
    for record in records:
        for sink in sinks:
            dist[sink].append(record)
    return dict(dist)

if __name__ == "__main_…
13 0 Open
Testing & modern typing medium

Use pytest fixture to mock a database connection in Python

This code shows how to use a pytest fixture and unittest.mock to replace a database connection with a Mock, enabling isolated tests without a real database.

pytest fixtures unittest.mock
Python
import pytest
import sqlite3
from unittest.mock import Mock

class Database:
    def __init__(self, connection):
        self.connection = connection

    def get_user(self, user_id):
        cursor = self.connection.cursor()
        cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
        return cursor.…
19 0 Open
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
Caching & Redis medium

Cache Penetration Null Object Mock in Python

Implement a cache that stores a null marker on misses to prevent repeated database hits, reducing cache penetration.

caching null-object ttl
Python
import time
from collections import defaultdict
from typing import Any, Optional


class Cache:
    def __init__(self):
        self.store: dict[str, Any] = {}
        self.ttl: dict[str, float] = {}
        self.null_marker = object()

    def get(self, key: str, ttl: int = 60, fallback:
            Any = None) -> An…
17 0 Open
Caching & Redis medium

How to Implement a Write-Through Cache in Python with a Mock Database

A thread-safe write-through cache that updates both cache and mock database atomically, computing values only after a successful write to the database.

caching write-through threading
Python
import threading
import time
import random


class WriteThroughCache:
    def __init__(self):
        self.cache = {}
        self.db = {}
        self.lock = threading.Lock()

    def write(self, key, value):
        with self.lock:
            # Simulate slow database write
            time.sleep(random.uniform(0.01…
12 0 Open
Observability & SRE easy

How to Check Service Readiness Dependencies in Python

This code simulates a readiness check for external dependencies (database, cache, queue) with mock availability data and reports readiness status.

readiness dependencies health-check
Python
import sys
from datetime import datetime


def check_dependencies(config):
    results = []
    for dep, required in config.items():
        available = mock_availability(dep)
        status = "READY" if available >= required else "NOT READY"
        results.append((dep, available, required, status))
    return result…
11 0 Open
Observability & SRE easy

How to Create a Deep Health Check Database in Python

Setup a SQLite-backed health check database, insert mock data with response times and statuses, and generate a report ordered by most recent check.

sqlite health-check database
Python
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path

DB_PATH = Path("deep_health_check.db")


def setup_database():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS health_checks (
            id INTEGER PRIMARY KEY AU…
14 0 Open
Observability & SRE easy

How to Mock Database Query Duration in Python

Simulate realistic database query durations with random jitter for testing dashboards, alerts, and SLO calculations.

observability mock metrics
Python
import random
import time


def mock_query_duration(db_name, avg_ms, jitter_ms=5, runs=3):
    """Simulate database query durations with realistic variation."""
    durations = []
    for _ in range(runs):
        # Base duration plus random jitter (can be negative)
        duration = avg_ms + random.uniform(-jitter_m…
14 0 Open
Microservices patterns easy

Cache-Aside Pattern in Python: Per-Service Mock

A Python mock of the cache-aside pattern for a single microservice—lazy-load from a database into an in-memory cache and invalidate on updates.

caching microservices cache-aside
Python
class ServiceCache:
    def __init__(self):
        self.database = {"user:1": "Alice", "user:2": "Bob", "user:3": "Charlie"}
        self.cache = {}

    def get_user(self, user_id):
        cache_key = f"user:{user_id}"
        if cache_key in self.cache:
            print(f"CACHE HIT: {cache_key}")
            retu…
13 0 Open
Microservices patterns easy

How to Demonstrate the Shared Database Antipattern in Python

This code simulates a shared database where multiple services write and read the same SQLite table, illustrating tight coupling and its pitfalls.

microservices database antipatterns
Python
import sqlite3
from pathlib import Path

def create_shared_db(db_path: Path) -> None:
    """Mock demonstrating the shared database antipattern where multiple
    services access the same database, causing tight coupling."""
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    cur.execute("""
        CREATE…
13 0 Open
Microservices patterns medium

How to implement the Database per service pattern in Python

Simulate separate databases per microservice in Python using dataclasses and in-memory dictionaries, showing how services own their data independently.

microservices database-per-service dataclasses
Python
import json
from dataclasses import dataclass, asdict
from typing import Dict, List


@dataclass
class User:
    id: int
    name: str
    email: str


@dataclass
class Order:
    id: int
    user_id: int
    product: str
    amount: float


class UserServiceDB:
    """Simulates a separate database for the User servic…
12 0 Open
Big data & Spark easy

How to select specific columns in Python with SQLite

A reusable function that connects to a SQLite database and returns only the requested columns from a given table.

sqlite sql database
Python
import sqlite3

def select_pruned_columns(db_path, table, columns):
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        col_list = ", ".join(columns)
        query = f"SELECT {col_list} FROM {table}"
        return cursor.execute(query).fetchall()

if __name__ == "__main__":
    conn = sq…
15 0 Open
Database scaling & optimization easy

Build a Partial Index Mock in Python for Database Filtering

Simulate a partial database index by filtering keys with a predicate, then return a limited mock lookup dictionary.

partial-index database mock
Python
data = [
    "alpha", "beta", "gamma", "delta", "epsilon",
    "zeta", "eta", "theta", "iota", "kappa"
]

filtered_keys = [item for item in data if len(item) >= 5]

def mock_partial_index(keys, filter_func, limit=3):
    result = {}
    for key in keys:
        if not filter_func(key):
            continue
        res…
12 0 Open
Database scaling & optimization medium

Composite index leftmost prefix in Python

Simulate a composite index in SQLite and check whether query columns match the leftmost prefix rule for index usage.

sqlite indexes database
Python
import sqlite3


def get_indexed_columns(table_name):
    """Simulate a composite index by reading column names that start with 'idx_'."""
    conn = sqlite3.connect(":memory:")
    conn.execute(f"CREATE TABLE {table_name} (id INTEGER, idx_col1 TEXT, idx_col2 INTEGER, other TEXT)")
    conn.execute(f"CREATE INDEX idx_…
14 0 Open
Database scaling & optimization medium

Cross Shard Query Scatter Gather Mock in Python

Simulate a distributed database cross-shard query using a scatter-gather pattern with a mock Python implementation.

scatter-gather sharding distributed-systems
Python
from dataclasses import dataclass
from typing import List, Dict


@dataclass
class NodeResponse:
    node_id: int
    data: Dict[str, float]


def mock_query_shard(shard_id: int, shard_data: Dict[str, float], query: str) -> NodeResponse:
    """Simulate querying a single shard, returning matches whose value > 50."""
 …
13 0 Open
Database scaling & optimization medium

Database Helper in Python with SQLite Scaling Optimization

Build a beginner-friendly SQLite database helper class with WAL, indexed queries, and efficient batch inserts for scaling.

sqlite database scalability
Python
import sqlite3
from contextlib import contextmanager


class DatabaseHelper:
    """Beginner-friendly helper for SQLite database operations with scaling tips."""

    def __init__(self, db_path):
        self.db_path = db_path

    @contextmanager
    def connection(self):
        """Context manager for automatic comm…
14 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.