Reference library

Python Code Samples

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

23 matches
Functions & basics medium

How to Build a Subcommand Parser Tree with argparse in Python

Create a CLI with nested subcommands (like git) using argparse subparsers, where each subcommand maps to its own handler function.

argparse cli subparsers
Python
import argparse


def cmd_add(args):
    print(f"Adding {args.num1} + {args.num2} = {args.num1 + args.num2}")


def cmd_sub(args):
    print(f"Subtracting {args.num1} - {args.num2} = {args.num1 - args.num2}")


def main():
    parser = argparse.ArgumentParser(prog="calculator")
    subparsers = parser.add_subparsers(d…
12 0 Open
Files & data medium

Convert Image to ASCII Art in Python

Convert any image to ASCII art by resizing, converting to grayscale, and mapping pixel brightness to characters using Pillow.

image ascii-art pillow
Python
from PIL import Image
import sys

ASCII_CHARS = "@%#*+=-:. "

def resize_image(image, new_width=100):
    """Resize image maintaining aspect ratio."""
    width, height = image.size
    ratio = height / width
    new_height = int(new_width * ratio * 0.55)  # 0.55 adjusts for font aspect ratio
    return image.resize((…
51 0 Open
AI & LLM integration patterns medium

Circuit Breaker Pattern in Python for LLM API Calls

Implements a circuit breaker class that wraps LLM client calls to fail fast when the service is degrading, then recover automatically after a timeout.

circuit-breaker llm resilience
Python
import time

class CircuitBreaker:
    def __init__(self, failure_threshold=3, recovery_timeout=5):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.failure_count = 0
        self.state = "closed"
        self.last_failure_time = None

    def call(self, …
14 0 Open
AI & LLM integration patterns medium

How to implement exponential backoff for LLM API calls in Python

A decorator that retries flaky LLM API calls with exponential delay, using a mock client to demonstrate the pattern.

exponential-backoff retries llm
Python
import time
import random

class MockLLM:
    def call(self, prompt):
        if random.random() < 0.7:  # 70% chance of transient failure
            raise ConnectionError("API unavailable")
        return f"LLM response for: {prompt}"

def with_exponential_backoff(max_retries=5, base_delay=0.1):
    def decorator(fu…
14 0 Open
Automation & scripting medium

Download Images from a Web Page Automatically in Python

Scrape all images from a webpage, filter by extension, and save them to a local folder using requests and BeautifulSoup.

web-scraping requests beautifulsoup
Python
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import os

def download_images(url, output_folder="downloaded_images"):
    """Download all images from a given URL."""
    os.makedirs(output_folder, exist_ok=True)
    
    response = requests.get(url)
    response.raise_for_status()
    …
48 0 Open
Automation & scripting medium

How to Generate Project Statistics Including Lines of Code and Complexity in Python

Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.

code metrics lines of code cyclomatic complexity
Python
import os
from pathlib import Path

def count_lines_of_code(filepath):
    """Counts lines of code in a Python file, excluding blank lines and comments."""
    try:
        with open(filepath, 'r') as f:
            lines = f.readlines()
        code_lines = [line for line in lines if line.strip() and not line.strip()…
40 0 Open
Automation & scripting medium

How to apply Kubernetes YAML files from a folder in Python

Uses the Kubernetes Python client to apply all YAML manifests in a directory, with sorted processing and per-file error handling.

kubernetes yaml automation
Python
import os
import yaml
from kubernetes import client, config
from kubernetes.utils import create_from_yaml

def apply_yaml_folder(folder_path):
    """Apply all YAML files in a folder using the Kubernetes mock client."""
    # Load mock configuration
    config.load_kube_config()
    k8s_client = client.ApiClient()

  …
12 0 Open
Cloud + Python medium

Build a URL Shortener Client with Python

A Python class that shortens long URLs and resolves short codes using a REST API built with requests.

url shortener api
Python
import json
import sys
import requests

class URLShortenerClient:
    def __init__(self, base_url="http://tinyurl.com"):
        self.base_url = base_url

    def shorten_url(self, long_url):
        payload = {"url": long_url}
        headers = {"Content-Type": "application/json"}
        response = requests.post(f"{…
57 0 Open
Cloud + Python medium

Exponential Backoff with Jitter for Cloud API Calls in Python

A Python snippet demonstrating exponential backoff with jitter for retrying transient cloud API failures, using a simulated client that has a configurable success rate.

retry backoff jitter
Python
import random
import time


def exponential_backoff_with_jitter(retries=5, base_delay=0.5, max_delay=4.0, jitter_factor=0.3):
    for attempt in range(1, retries + 1):
        delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
        jitter = delay * random.uniform(-jitter_factor, jitter_factor)
        effect…
18 0 Open
Cloud + Python medium

How to Mock Azure Key Vault Secret Get in Python

Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.

azure key-vault unittest
Python
import unittest
from unittest.mock import MagicMock, patch


def get_secret(key_vault_client, secret_name):
    """Retrieve a secret value from an Azure Key Vault client."""
    secret = key_vault_client.get_secret(secret_name)
    return secret.value


class TestKeyVaultSecretGet(unittest.TestCase):
    def test_get_…
13 0 Open
Cloud + Python medium

How to mock boto3 S3 upload in Python

Shows how to mock the boto3 S3 client with unit tests and wrap an upload function to return a dictionary with status details.

boto3 s3 mocking
Python
import boto3
from unittest.mock import Mock, patch

class S3Uploader:
    def __init__(self, bucket_name):
        self.bucket_name = bucket_name
        self.s3 = boto3.client("s3", region_name="us-east-1")

    def upload_file(self, local_path, s3_key):
        self.s3.upload_file(local_path, self.bucket_name, s3_ke…
12 0 Open
Modern tooling medium

How to Mock CLI Output in Typer with unittest.mock

Mock and capture Typer CLI output using unittest.mock.patch and io.StringIO for testing command-line applications.

typer cli testing
Python
import typer
from unittest.mock import patch
import io

app = typer.Typer()

@app.command()
def greet(name: str, age: int = 18, uppercase: bool = False):
    """Greet a person with optional formatting."""
    message = f"Hello {name}, age {age}"
    if uppercase:
        message = message.upper()
    typer.echo(messag…
11 0 Open
Modern tooling medium

How to mock argparse nested subparsers in Python

Build an argparse parser with nested subparsers and test it using unittest.mock.patch for sys.argv and sys.stdout.

argparse subparsers unittest
Python
import argparse
from unittest.mock import patch
from io import StringIO

def build_parser():
    parser = argparse.ArgumentParser(prog="app")
    subparsers = parser.add_subparsers(dest="command", required=True)

    # Outer subparser
    outer = subparsers.add_parser("outer")
    outer_sub = outer.add_subparsers(dest…
15 0 Open
API design & gRPC medium

How to Implement Content Negotiation with JSON and XML in Python

Build an HTTP server that returns JSON or XML responses based on the client's Accept header, with a 406 response for unsupported formats.

http-server content-negotiation json
Python
import json
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, HTTPServer


class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        data = {"message": "Hello, world!"}
        accept_header = self.headers.get("Accept", "")

        if "application/json" in accept_hea…
11 0 Open
API design & gRPC medium

How to mock Server-Sent Events (SSE) in Python

A minimal HTTP server that streams Server-Sent Events to clients, perfect for testing and development.

sse server-sent-events http
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading
import time

MESSAGES = iter([
    "data: Hello world\n\n",
    "data: Second message\n\n",
    "event: custom\n",
    "data: Custom event payload\n\n",
    "data: Final message\n\n"
])

class SSEHandler(BaseHTTPRequestHandler):
    def do_GET…
14 0 Open
API design & gRPC medium

Implement If-Match Precondition Update in Python

A mock resource store that uses the If-Match header's ETag to guard updates, preventing overwrites from stale clients.

api etag optimistic-concurrency
Python
from dataclasses import dataclass
from typing import Optional


@dataclass
class Resource:
    id: str
    version: int = 1
    data: str = ""
    etag: str = "etag-1"


class MockResourceStore:
    def __init__(self):
        self.resources = {}

    def update(self, resource_id: str, new_data: str, if_match: Optiona…
13 0 Open
Reliability & rate limiting medium

How to Implement a Token Bucket Rate Limiter per Client IP in Python

Implements a simple sliding-window rate limiter using a dictionary of timestamp lists per client IP to limit requests per window.

rate-limiting sliding-window ip
Python
from time import time
from collections import defaultdict

class RateLimiter:
    def __init__(self, max_requests: int, window_seconds: int):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.clients = defaultdict(list)

    def allow(self, ip: str) -> bool:
        now…
13 0 Open
Microservices patterns medium

How to Build an OAuth Client Credentials Mock Server in Python

A minimal HTTP mock server implementing the OAuth 2.0 client credentials grant for local testing and microservice development.

oauth mock-server microservices
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

TOKENS = {"valid_token": "demo_access_token", "client_id": "my_service"}

class OAuthHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == "/oauth/token":
            length = int(self.headers.get("Content-Length", 0))
  …
14 0 Open
Big data & Spark medium

How to Build a DAG Execution Stage Calculator in Python

Computes the execution stages of a directed acyclic graph (DAG) by grouping nodes that become ready simultaneously using topological sorting with Kahn's algorithm.

dag topological-sort kahn-algorithm
Python
from collections import defaultdict, deque


def get_stages(edges):
    """Return list of stages, where each stage is a list of nodes
    that become ready at the same time in a DAG."""
    graph = defaultdict(list)
    in_degree = defaultdict(int)
    nodes = set()

    for src, dst in edges:
        graph[src].appen…
15 0 Open
ML engineering pipelines medium

How to Mock MLflow Model Registration in Python

Build a lightweight in-memory mock of MLflow's MlflowClient to test model registration, versioning, and stage transitions without a tracking server.

mlflow mocking model-registry
Python
from mlflow.tracking import MlflowClient
from mlflow.entities import ModelVersion, Model


class MockMlflowClient:
    """Minimal mock of MlflowClient's model registration methods."""
    
    def __init__(self):
        self.registered_models = {}
        self.model_versions = {}
    
    def register_model(self, mod…
14 0 Open
Auth & security at scale medium

How to Mock an mTLS Client Certificate in Python

Create a self-signed client certificate and key with OpenSSL, load them into an SSL context, and simulate an mTLS handshake in Python for testing.

mtls ssl certificates
Python
import ssl
import socket
import subprocess
import tempfile
from pathlib import Path

def create_mock_certificates():
    """Generate self-signed client certificate and key for mTLS testing."""
    with tempfile.TemporaryDirectory() as tmpdir:
        cert_path = Path(tmpdir) / "client.crt"
        key_path = Path(tmpd…
14 0 Open
Auth & security at scale medium

Mock client credentials machine auth in Python

This code simulates the OAuth2 client-credentials flow for service-to-service calls, generating a mock bearer token with expiry and caching, plus a revoke method, using only the standard library.

oauth2 auth mock
Python
import time
import hashlib
import secrets

class MachineAuth:
    """Mock client-credentials machine auth for service-to-service calls."""
    
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self._token = None
        self._expire…
15 0 Open
Production deployment patterns medium

How to Mock Kubernetes Secret Mounts in Python

Create and inspect a mock Kubernetes secret volume mount using the official client library and unittest.mock.

kubernetes mock testing
Python
import json
from kubernetes import client, config, watch
from unittest.mock import Mock, patch

def create_mock_mount_spec():
    """Create a mock Kubernetes secret volume mount."""
    mock_client = Mock()
    mock_client.api_version = "v1"
    mock_client.kind = "Secret"
    mock_client.metadata = {"name": "my-secre…
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.