Reference library

Python Code Samples

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

11 matches
Dictionaries & sets easy

How to Count Words and Find Common Words in Python with Dictionaries and Sets

Build a simple text processor that counts unique words with dictionaries and finds common words across text halves using sets.

dictionaries sets word-count
Python
def process_text(text):
    """Process text: count unique words with counts, find common words."""
    words = text.lower().replace(",", "").replace(".", "").split()
    
    word_counts = {}
    for word in words:
        word_counts[word] = word_counts.get(word, 0) + 1
    
    total_words = len(words)
    unique_wo…
13 0 Open
OOP & classes easy

How to Copy Class Instances in Python: Shallow vs Deep Copy

Use copy.copy and copy.deepcopy to clone class instances, showing how nested objects are shared or duplicated.

copy deepcopy shallow copy
Python
import copy


class Config:
    def __init__(self):
        self.settings = {"theme": "dark", "language": "en"}


if __name__ == "__main__":
    original = Config()

    shallow_copy = copy.copy(original)
    deep_copy = copy.deepcopy(original)

    shallow_copy.settings["theme"] = "light"
    deep_copy.settings["them…
13 0 Open
Git + Python easy

How to Make a Shallow Clone of an Object in Python

Demonstrates using copy.copy() to create a shallow clone of a Python object, showing how nested mutable data is shared while top-level attributes are independent.

copy shallow-copy clone
Python
import copy


class Config:
    def __init__(self):
        self.settings = {"volume": 50}
        self.user = "admin"


def demonstrate_shallow_copy():
    original = Config()
    shallow = copy.copy(original)

    # Mutating nested object is visible in both (shallow copy share it)
    shallow.settings["volume"] = 90…
14 0 Open
System design patterns medium

Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States

Implement a circuit breaker with closed, open, and half-open states to prevent repeated calls to failing services and allow recovery after a timeout.

circuit-breaker resilience fault-tolerance
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3, timeout_seconds=5):
        self.failure_threshold = failure_threshold
        self.timeout_seconds = timeout_seconds
        self.state = "closed"
        self.failure_count = 0
        self.last_failure_time = None

    def record_success(self):
     …
14 0 Open
API design & gRPC medium

How to Build a Hypermedia Collection Resource in Python

Creates a paginated hypermedia collection resource with HATEOAS links and embedded items.

hateoas hal pagination
Python
import json
import math


class HypermediaCollection:
    """A mock hypermedia collection resource."""

    def __init__(self, items, base_url="/api/items"):
        self.items = items
        self.base_url = base_url

    def to_dict(self, page=1, per_page=3):
        total = len(self.items)
        pages = math.ceil…
14 0 Open
Reliability & rate limiting medium

Circuit breaker failure threshold count in Python

Track consecutive or time-windowed failures with a deque to open a circuit breaker and auto-recover to half-open after a cooldown.

circuit-breaker resilience deque
Python
from collections import deque
from time import time, sleep


class CircuitBreaker:
    def __init__(self, failure_threshold: int = 5, recovery_time: float = 10.0):
        self.failure_threshold = failure_threshold
        self.recovery_time = recovery_time
        self.failures: deque[float] = deque()
        self.st…
16 0 Open
Reliability & rate limiting medium

How to Implement a Circuit Breaker in Python

A Python dataclass that provides circuit breaker logic with closed, open, and half-open states to fail fast on repeated errors.

circuit-breaker resilience fault-tolerance
Python
from dataclasses import dataclass
from datetime import datetime, timedelta
import time


@dataclass
class CircuitBreaker:
    failure_threshold: int = 3
    timeout_seconds: float = 5.0
    failures: int = 0
    state: str = "closed"
    last_failure: datetime = None

    def call(self, func):
        if self.state ==…
15 0 Open
Reliability & rate limiting medium

How to Mock a Circuit Breaker Reset Timeout in Python

This code implements a simple circuit breaker with a reset timeout test, simulating a flaky service to show half-open state transitions.

circuit-breaker reliability mock-testing
Python
import time
import random


class CircuitBreaker:
    def __init__(self, failure_threshold=3, reset_timeout=5):
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self.failure_count = 0
        self.last_failure_time = None
        self.state = "CLOSED"  # CLOSED (nor…
15 0 Open
ML engineering pipelines easy

Champion Challenger Deployment Mock in Python

Simulates an A/B champion-challenger ML deployment workflow — comparing two mock model accuracies and deciding which to promote to production.

ml deployment champion-challenger
Python
import random
import time

class ModelMocker:
    def __init__(self, name="Model", accuracy=0.85):
        self.name = name
        self.accuracy = accuracy

    def predict(self, data):
        """Simulate prediction with some randomness."""
        time.sleep(0.005)  # simulate compute time
        return 1 if rando…
13 0 Open
Auth & security at scale medium

ACME LetsEncrypt Mock Challenge Server in Python

A minimal HTTP server that serves key authorizations for ACME/Let's Encrypt DNS-01 or HTTP-01 challenges during testing and validation.

acme letsencrypt http-server
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

# In-memory store simulating the ACME challenge token -> key authorization pair
challenge_store = {
    "token_example": "token_example.key_authorization"
}

class AcmeChallengeHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Extra…
15 0 Open
Auth & security at scale easy

How to Generate PKCE Code Challenge in Python

This Python script generates a PKCE code verifier and its corresponding S256 code challenge for secure OAuth2 authorization flows.

pkce oauth2 security
Python
import base64
import hashlib
import os
import secrets
import string

def generate_code_verifier(length=64):
    alphabet = string.ascii_letters + string.digits + "-._~"
    return "".join(secrets.choice(alphabet) for _ in range(length))

def generate_code_challenge(code_verifier, method="S256"):
    if method == "S256…
15 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.