Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
Build a Recipe Runner Mock in Python
A Python script that mocks a command runner recipe system: maps recipe names to shell commands, executes them with subprocess, and prints the output and exit code.
import subprocess
import sys
def run_recipe(recipe: str) -> None:
"""Simulate a command runner recipe by printing the command and exit code."""
print(f"Running recipe: {recipe}")
result = subprocess.run(recipe, shell=True, capture_output=True, text=True)
print(f"Exit code: {result.returncode}")
i…
How to Build a Chainable Filter Helper in Python
A beginner-friendly dataclass helper that chains filters, uniqueness, and slicing on any sequence, returning a plain list at the end.
from dataclasses import dataclass
from typing import Callable, Iterator, Sequence, TypeVar
T = TypeVar("T")
@dataclass
class FilterAssistant:
"""Beginner-friendly helper to filter any collection."""
data: Sequence[T]
def where(self, predicate: Callable[[T], bool]) -> "FilterAssistant":
return …
How to Generate a Mock devcontainer.json Config in Python
Build a reproducible devcontainer.json file with Python, composing name, image, extensions, forwarded ports, and a post-create command as a dict.
import json
from pathlib import Path
def create_devcontainer_config(
image: str = "mcr.microsoft.com/devcontainers/python:3.11",
name: str = "python-dev-container",
ports: list[int] | None = None,
post_create: str | None = None,
) -> dict:
config = {
"name": name,
"image": image,
…
How to Mock BugSnag Notify in Python
Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.
import mock
bugsnag = mock.MagicMock()
def notify_error(message, severity="error"):
bugsnag.notify(message, severity=severity)
if __name__ == "__main__":
notify_error("Test error", severity="warning")
bugsnag.notify.assert_called_once_with("Test error", severity="warning")
print("Mocked BugSnag noti…
How to Mock OpenTelemetry Tracer Setup in Python
Set up a mock OpenTelemetry tracer with an in-memory span exporter to capture spans for testing and debugging.
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 setup_tracer():
provider = TracerProvider()
exporter = InMemorySpanExpo…
How to Mock Poetry pyproject.toml Dependencies Sections in Python
Parse and extract dependency lists from Poetry-style pyproject.toml text using Python's standard library.
from pathlib import Path
import re
def parse_pyproject_dependencies(text):
"""Extract dependencies from a pyproject.toml style text."""
lines = text.splitlines()
sections = {
"dependencies": [],
"dev": [],
"optional": [],
}
current_section = None
patterns = {
…
How to build a tox multi-env matrix with mock config in Python
Simulate a tox multi-environment matrix by validating environment names and grouping extras into a readable matrix structure.
```python
import tox
def run_tox_matrix(mock_envs):
"""Simulate a tox multi-env configuration and verify mock choices."""
config = {
"tox": {
"envlist": mock_envs,
"config": {
"basepython": "python3.9",
"deps": ["pytest", "mock"],
},
…
Browse by section
Each section groups closely related Python snippets.
Modern tooling — Python code examples
What you will find here
This page collects modern tooling snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.