Reference library

Python Code Samples

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

7 matches
Automation & scripting medium

Build a Complete Web Scraper with Requests and BeautifulSoup in Python

Scrape multiple paginated pages from a website using Requests and BeautifulSoup, with retry logic, error handling, and CSV export.

web scraping requests beautifulsoup
Python
import requests
from bs4 import BeautifulSoup
import csv
import time
from typing import List, Dict, Optional

class WebScraper:
    def __init__(self, base_url: str, output_file: str = "scraped_data.csv"):
        self.base_url = base_url
        self.output_file = output_file
        self.session = requests.Session()…
99 0 Open
Git + Python medium

How to Archive a Repository as a ZIP in Python

Create a ZIP archive of a repository directory with a mock export, skipping hidden files and __pycache__ folders.

zipfile os.walk archiving
Python
import zipfile
import io
import os
from pathlib import Path


def archive_repo_mock(repo_path, output_path="repo_archive.zip"):
    """Create a zip archive of a repository directory (mock export)."""
    repo = Path(repo_path)
    if not repo.exists():
        raise FileNotFoundError(f"Repository not found: {repo}")

…
13 0 Open
System design patterns medium

How to Build a Pipe and Filter Text Processing Chain in Python

A functional pipe-and-filter chain that transforms text through uppercase, whitespace normalization, number removal, stopword filtering, and file export.

pipeline text-processing functional
Python
import re
import sys


def pipe_filter_chain(stream):
    def uppercase(text):
        return text.upper()

    def strip_whitespace(text):
        return " ".join(text.split())

    def remove_numbers(text):
        return re.sub(r"\d+", "", text)

    def remove_stopwords(text, stopwords={"the", "and", "of", "in"}):…
16 0 Open
Observability & SRE medium

Export Metrics with OTLP Mock in Python

Simulates system metric collection and exports them as an OTLP-like JSON payload using only Python's standard library.

otlp metrics observability
Python
from dataclasses import dataclass, asdict
import json
import random
import time


@dataclass
class Metric:
    name: str
    value: float
    timestamp: int
    unit: str = "1"


def collect_system_metrics() -> list[Metric]:
    """Mock metric collection for OTLP export simulation."""
    now = int(time.time())
    re…
12 0 Open
Observability & SRE medium

How to Create a Mock OpenTelemetry Trace in Python

Create a mock OpenTelemetry trace in memory to test span creation, attributes, and parent-child relationships without exporting to a backend.

opentelemetry tracing testing
Python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter


def create_mock_trace():
    tracer_provider = TracerProvider()
    span_exporter =…
13 0 Open
ML engineering pipelines medium

How to Create a Mock ONNX Model in Python

Build and export a minimal mock ONNX model with a Reshape and Gemm layer using the onnx helper API.

onnx model-export mlops
Python
import onnx
import numpy as np
from onnx import helper, TensorProto

def create_mock_model():
    # Define input and output tensors
    input_tensor = helper.make_tensor_value_info('input', TensorProto.FLOAT, [1, 3, 224, 224])
    output_tensor = helper.make_tensor_value_info('output', TensorProto.FLOAT, [1, 10])

   …
16 0 Open
Production deployment patterns medium

How to Mock Kubernetes Services with a ClusterIP Registry in Python

Simulate Kubernetes service discovery by assigning ClusterIP addresses to dataclass-defined services, with JSON export for inspection or testing.

kubernetes clusterip mock
Python
import json
from dataclasses import dataclass, asdict
from typing import Dict, Optional


@dataclass
class Service:
    name: str
    namespace: str
    cluster_ip: str
    selector: Dict[str, str]
    port: int
    target_port: Optional[int] = None


class ClusterIPServiceRegistry:
    _ip_counter = 0

    def __init…
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.