Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Write a Python Decorator with functools.wraps
Create a decorator that wraps a function while preserving its metadata using functools.wraps.
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def greet(name):
"""Return a friendly greeting."""
return f"Hello, {name}!"
if __name__ == "__main__":…
How to Sort Data in Python with a Class Helper
This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.
class DataSorter:
def __init__(self, data):
self.data = data
def sort_numbers(self, reverse=False):
return sorted(self.data, reverse=reverse)
def sort_strings_ignore_case(self, reverse=False):
return sorted(self.data, key=str.lower, reverse=reverse)
def sort_dicts_by_key(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 Mock subprocess Calls in Python with unittest.mock
A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.
import subprocess
from unittest.mock import patch, Mock
def run_vagrant(action: str) -> str:
result = subprocess.run(
["vagrant", action],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip()
def vagrant_wrapper(action: str) -> str:
if action n…
How to Build a Git Helper Class in Python
A beginner-friendly GitHelper class that wraps common git commands (status, log, branch) into reusable Python methods with structured output.
import subprocess
import json
from pathlib import Path
class GitHelper:
def __init__(self, repo_path="."):
self.repo = Path(repo_path)
def run(self, *args):
result = subprocess.run(
["git", *args],
cwd=self.repo,
capture_output=True,
text=True,…
How to Mock a Metrics Decorator in Python with unittest.mock
This code demonstrates a timing decorator that wraps a function to measure execution time and prints the duration, with a unit test using unittest.mock to patch the print function and assert it was called.
import time
from functools import wraps
from unittest.mock import patch
def add_metrics(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.6f}s…
How to Wrap Message Attributes in a CloudEvent with Python
Create a minimal CloudEvent dataclass that wraps arbitrary message attributes into a JSON envelope, matching CloudEvents 1.0 spec.
import json
from dataclasses import dataclass, field, asdict
from typing import Any, Dict
from datetime import datetime, timezone
@dataclass
class CloudEvent:
message_attributes: Dict[str, Any] = field(default_factory=dict)
def wrap(self, event_id: str, source: str, event_type: str, data: Any):
self…
How to Mock Cache Tag Invalidation in Python
Use unittest.mock.patch with wraps to verify tagged cache entries are invalidated correctly.
import unittest
from unittest.mock import patch
def get_cached_data(cache, key):
"""Return data from cache if present and valid, else None."""
if cache.get(key, {}).get("valid", False):
return cache[key]["data"]
return None
def invalidate_tag_mock(cache, tag):
"""Invalidate all cache entries …
Mocking a Metrics Gauge's set_value Method in Python
Demonstrates using unittest.mock.Mock with wraps to intercept a gauge's set_value call while verifying arguments and preserving real behavior.
from unittest.mock import Mock
class MetricsGauge:
def __init__(self, name):
self.name = name
self.value = 0.0
def set_value(self, new_value):
self.value = float(new_value)
return self.value
# Usage demonstration with a mock
gauge = MetricsGauge("cpu_usage")
gauge_mock = Mock…
Fallback cached response mock in Python
Wraps a mock function with a fallback to a real service and caches results to mask transient failures.
import time
from functools import wraps
class CachedMock:
def __init__(self, cache_ttl=5):
self.cache = {}
self.cache_ttl = cache_ttl
def get(self, key):
cached = self.cache.get(key)
if cached and time.time() - cached["timestamp"] < self.cache_ttl:
return cached["v…
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.