Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Find Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
def find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(n…
Implement Insert Delete GetRandom O(1) in Python
Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.
import random
class RandomizedSet:
def __init__(self):
self.values = []
self.index_map = {}
def insert(self, val):
if val in self.index_map:
return False
self.index_map[val] = len(self.values)
self.values.append(val)
return True
def delete(self…
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.
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, …
How to Build a Data Helper for LLM Prompts in Python
A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Simple helper class for working with data in AI/LLM pipelines."""
def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
self.data = data or {}
def flatten(self, prefix: str = "") -> Dict[str, Any]…
How to check Python files for common coding mistakes
Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.
import ast
import os
import sys
def check_file(filepath):
try:
with open(filepath) as f:
code = f.read()
tree = ast.parse(code, filename=filepath)
except SyntaxError as e:
print(f"{filepath}: SyntaxError: {e.msg}")
return
issues = []
for node in ast.wal…
Mount ISO Loop Device Mock Script in Python
Simulate ISO mounting with a loop device using a mock class — useful for testing scripts that depend on mount/unmount without actual system privileges.
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path
@dataclass
class LoopDevice:
path: str
iso_path: str
mounted: bool = False
def mount(self, mount_point: str):
if self.mounted:
raise RuntimeError(f"Loop device {self.path} already mounted")
…
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.
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"{…
Mock Google Pub/Sub publish and pull in Python
A lightweight in-memory mock of Google Pub/Sub with publisher/subscriber classes to test topic-based fan-out and message pulling without real infrastructure.
import json
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class Message:
data: str
attributes: dict[str, str] = field(default_factory=dict)
message_id: str | None = None
ack_id: str | None = None
class MockPublisher:
…
How to Build a Producer-Consumer Pattern with asyncio.Queue in Python
This code implements a classic producer-consumer pattern using asyncio.Queue to coordinate one producer task that generates items and two consumer tasks that process them concurrently, with a sentinel value to signal completion.
import asyncio
import random
async def producer(queue, item_count):
for i in range(item_count):
item = random.randint(1, 100)
await queue.put(item)
print(f"Produced: {item}")
await asyncio.sleep(0.1)
await queue.put(None) # Sentinel to signal end
async def consumer(queue, n…
How to Reduce Instance Memory with __slots__ in Python
Demonstrates that classes with __slots__ use less memory per instance than regular classes because they skip the instance __dict__.
class SlottedPoint:
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class RegularPoint:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
if __name__ == "__main__":
regular = RegularPoint(1, 2, 3)…
How to Mock an Object Method in Python unittest
Mock a method on an instance or class with @patch.object, set its return value, and assert its call arguments in Python unittest.
import unittest
from unittest.mock import patch
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
class TestCalculator(unittest.TestCase):
def test_add_normal(self):
calc = Calculator()
result = calc.add(2, 3)
self.asse…
How to Use Stubs, Fakes, Spies, and Mocks in Python Testing
Implement four types of test doubles — stubs, fakes, spies, and mocks — as subclasses of a PaymentGateway interface to replace real dependencies during testing.
class PaymentGateway:
def charge(self, amount):
raise NotImplementedError
class StubPaymentGateway(PaymentGateway):
"""Returns a fixed response without any logic."""
def charge(self, amount):
return {"success": True, "transaction_id": "stub-12345"}
class FakePaymentGateway(PaymentGatewa…
How to Build an Adapter to Translate External API Responses in Python
Build an adapter class that translates a mock external API's response shape into your internal representation, keeping callers decoupled from the external contract.
import json
from typing import Dict, Any
class ExternalAPI:
"""Mock external service returning a different data shape."""
def get_user(self, user_id: int) -> Dict[str, Any]:
return {
"id": user_id,
"full_name": "Jane Doe",
"email_address": "jane@example.com",
…
How to Build an Immutable Money Value Object in Python
Implement an immutable Money class with rounded decimal amounts, currency, safe equality, and hashing for use as a value object.
class Money:
def __init__(self, amount: float, currency: str):
object.__setattr__(self, "_amount", round(amount, 2))
object.__setattr__(self, "_currency", currency)
def __setattr__(self, name, value):
raise AttributeError(f"Money is immutable: cannot set '{name}'")
def __delattr__…
How to Implement CQRS with Separate Read and Write Models in Python
Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.
from dataclasses import dataclass, field
from typing import List, Dict, Optional
@dataclass
class OrderWriteModel:
order_id: int
customer: str
items: List[str] = field(default_factory=list)
def add_item(self, item: str) -> None:
self.items.append(item)
@dataclass
class OrderReadModel:
…
How to Implement the Abstract Factory Pattern in Python
Implements the Abstract Factory pattern to create families of related GUI objects (buttons, checkboxes) without specifying their concrete classes.
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def render(self):
pass
class Checkbox(ABC):
@abstractmethod
def render(self):
pass
class WindowsButton(Button):
def render(self):
return "Rendering Windows-style button"
class WindowsCheckbox(Chec…
Inbox pattern consumer dedupe mock in Python
Implements a mock inbox consumer that deduplicates incoming messages by ID, with automatic eviction of old seen IDs to prevent unbounded memory growth.
import json
from collections import deque
from dataclasses import dataclass, field
from hashlib import sha256
from typing import Any
@dataclass
class InboxConsumer:
max_seen: int = 1000
seen_ids: set = field(default_factory=set)
seen_history: deque = field(default_factory=deque)
def _mark_seen(self,…
Microkernel Plug-in Core Mock in Python
Implements a minimal microkernel plug-in core that registers, unregisters, and executes synchronous or asynchronous plugins via a pluggable manager class.
import json
import abc
import inspect
class MicrokernelCore(abc.ABC):
def __init__(self):
self._plugins = {}
def register(self, name, plugin):
self._plugins[name] = plugin
def unregister(self, name):
return self._plugins.pop(name, None)
def execute(self, name, *args, **kwa…
Template Method Workflow Steps Base Class in Python
Define a reusable workflow skeleton in a base class and let subclasses fill in each step with the Template Method design pattern.
from abc import ABC, abstractmethod
class DataPipeline(ABC):
"""Template Method pattern: defines a workflow skeleton."""
def run(self):
"""Template method - defines the algorithm's structure."""
result = {"extracted": False, "transformed": False, "loaded": False}
raw_data = self._ext…
How to Build a Flow Control Credit Window in Python
A Python class that reserves, confirms, releases, and settles credit to limit message flow and prevent overload in streaming pipelines.
class CreditWindow:
def __init__(self, max_credit=1000):
self.max_credit = max_credit
self.used_credit = 0
self.pending_credit = 0
def try_reserve(self, amount):
available = self.max_credit - self.used_credit - self.pending_credit
if available >= amount:
…
How to Implement an Outbox Table Poll Publisher in Python
This code simulates an outbox pattern with a class that polls for pending records and publishes them as JSON messages, removing only those that are due.
import time
import json
from dataclasses import dataclass, asdict
from datetime import datetime, timedelta
@dataclass
class OutboxRecord:
id: int
topic: str
payload: dict
created_at: datetime
class OutboxPollPublisher:
def __init__(self, poll_interval_seconds=1):
self.poll_interval = poll…
How to Track Session Windows with Gap Timeout in Python
A Python class that groups events into sessions, closing a session when the gap between events exceeds a timeout threshold.
import time
class SessionWindow:
"""Track sessions with a gap timeout (mock)."""
def __init__(self, timeout_seconds=5):
self.timeout = timeout_seconds
self.session_start = None
self.last_event_time = None
self.event_count = 0
self.events = []
def add_event…
How to mock a CQRS projector read model update in Python
Build a CQRS projector class that maintains denormalized read models by applying domain events in a mock order-processing service.
from dataclasses import dataclass, field
from typing import Dict, List, Optional
@dataclass
class OrderReadModel:
order_id: str
customer_name: str
total: float
status: str = "pending"
items: List[Dict] = field(default_factory=list)
def apply_event(self, event_type: str, payload: Dict) -> Non…
Kafka Consumer Poll Loop Mock in Python
Simulate a Kafka consumer poll loop with a mock class, process messages in batches, and commit offsets to understand streaming consumption patterns.
import time
class MockKafkaConsumer:
def __init__(self, topic, messages):
self.topic = topic
self.messages = list(messages)
self.position = 0
def poll(self, timeout_ms=100):
if self.position >= len(self.messages):
time.sleep(timeout_ms / 1000)
return []…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.