Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
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 Mock Twine Upload to TestPyPI in Python
Simulate a twine upload to TestPyPI with a dry-run mock function that validates distribution files and prints the intended upload action without any network call.
import subprocess
import sys
# Mock twine upload to TestPyPI using subprocess dry-run
def mock_twine_upload(dist_file: str, repo_url: str = "https://test.pypi.org/legacy/") -> None:
"""Simulate twine upload by checking dist file and printing intended action."""
if not dist_file.endswith((".whl", ".tar.gz")):
…
How to Mock a Fast uv pip sync in Python
Simulate a fast uv pip sync by mocking file operations and subprocess calls to test dependency installation workflows.
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
def uv_pip_sync_fast_install_mock(requirements_text: str) -> dict:
"""Simulate a fast uv pip sync by mocking file operations and subprocess calls."""
mock_dir = Path(tempfile.mkdtemp(prefix="uv_mock_"))
req_lines…
How to Mock a pipx Install Command in Python
Simulate a pipx install step by validating tool names and printing the exact command output a real pipx run would produce.
import subprocess
import sys
def install_with_pipx(tool_name: str) -> str:
"""
Mock a pipx install step by validating the tool name and
simulating the installation command output.
"""
allowed_tools = {"black", "flake8", "mypy", "ruff"}
if tool_name not in allowed_tools:
raise ValueErr…
How to Mock a pyenv Local Version File in Python
Read and write a mock .python-version file using the pathlib module and tempfile for isolated testing.
import json
import tempfile
from pathlib import Path
def read_pyenv_local(directory: Path) -> str:
"""Read the .python-version file in the given directory."""
version_file = directory / ".python-version"
if not version_file.exists():
return "no-version-file"
return version_file.read_text().st…
How to Mock docker compose up Healthcheck in Python
Simulate docker compose up with a healthcheck cycle using Python loops, delays, and simulated service statuses.
import subprocess
import time
def run_healthcheck():
"""Mock a docker compose up with a healthcheck cycle."""
services = ["web", "db", "cache"]
print("Starting docker compose services...")
for service in services:
print(f"[{service}] starting...")
time.sleep(0.1)
print(f"[…
How to Mock isort Output to Test Import Sorting in Python
Uses isort with check mode and a unittest mock to verify whether a Python source string has correctly sorted imports.
import isort
from unittest.mock import patch
code = """
import os
import sys
import json
import pathlib
"""
def check_imports_sorted(code_str):
with patch("isort.api.output") as mock_output:
isort.code(code_str, check=True, show_diff=True)
return mock_output.called
if __name__ == "__main__":
…
How to Mock setuptools_scm get_version in Python
This code demonstrates how to mock setuptools_scm.get_version in Python using unittest.mock.patch to test version retrieval logic without installing or relying on the actual package.
```python
from unittest.mock import patch
def get_version_from_scm():
try:
import setuptools_scm
return setuptools_scm.get_version()
except (ImportError, LookupError):
return None
if __name__ == "__main__":
with patch("setuptools_scm.get_version", return_value="1.2.3"):
pr…
How to Parametrize Tests in Python with pytest
This code demonstrates how to use pytest's @pytest.mark.parametrize decorator to run a single test function against multiple input sets, ensuring comprehensive coverage with minimal code duplication.
import pytest
def multiply(a, b):
return a * b
@pytest.mark.parametrize("x, y, expected", [
(2, 3, 6),
(4, 5, 20),
(0, 10, 0),
(7, 1, 7),
])
def test_multiply(x, y, expected):
result = multiply(x, y)
assert result == expected, f"multiply({x}, {y}) = {result}, expected {expected}"
if _…
How to Parse Taskfile YAML in Python
Load a Taskfile.yaml with PyYAML and simulate task execution by returning each task's commands.
import yaml
from pathlib import Path
def load_taskfile(taskfile_path: str) -> dict:
"""Load and parse a Taskfile.yaml file into a dict."""
data = Path(taskfile_path).read_text()
return yaml.safe_load(data)
def run_task(taskfile: dict, task_name: str) -> dict:
"""Simulate running a task by returning i…
How to Parse and Extract Nested Data in Python
Load JSON files with Path and recursively extract values by key from nested Python structures using modern typing and standard library.
import json
from pathlib import Path
from typing import Any, Dict, List, Union
def load_data(filepath: Union[str, Path]) -> Union[Dict[str, Any], List[Any]]:
"""Load JSON data from a file with modern Path handling."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not f…
How to Read the Python Path from VS Code settings.json in Python
This code loads VS Code's settings.json file and extracts the python.defaultInterpreterPath value, with a mock demonstration for testing.
import json
from pathlib import Path
from unittest.mock import patch
def read_vscode_python_path(settings_path: Path) -> str:
"""Extract python.defaultInterpreterPath from VS Code settings.json."""
with open(settings_path, "r") as f:
settings = json.load(f)
return settings.get("python", {}).get("d…
How to Run Coverage Report and Generate HTML in Python
Use the coverage module to measure test coverage, save the report, and generate an HTML report in Python.
import coverage
import unittest
def add(a, b):
return a + b
class TestAdd(unittest.TestCase):
def test_add_positive(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
cov = coverage.Coverage(source=["__main__"])
cov.start()
suite = unittest.defaultTestLoader.loadTestsFro…
How to Save and Load JSON Files in Python
Create a simple data helper to save Python dictionaries as pretty-printed JSON files and load them back reliably using pathlib and the stdlib json module.
import json
from pathlib import Path
from typing import Any
def save_json(data: Any, filename: str) -> None:
"""Save data as pretty-printed JSON to the current directory."""
path = Path(filename)
with path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def lo…
How to Type Check a Mock with pyright in Python
Shows how pyright validates a mock function against a TypedDict and Callable signature before runtime.
from typing import TypedDict, Callable
class User(TypedDict):
id: int
name: str
def get_user_name(user_id: int, get_user: Callable[[int], User]) -> str:
user = get_user(user_id)
return user["name"]
def mock_get_user(user_id: int) -> User:
return {"id": user_id, "name": f"User {user_id}"}
if…
How to Use prompt_toolkit Autocomplete in Python
Demonstrates an interactive command-line prompt with autocomplete using prompt_toolkit's WordCompleter and a mock dataset.
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
def main():
"""Demo of prompt_toolkit autocomplete with a mock dataset."""
# A simple mock "database" of programming languages
languages = [
"Python", "Java", "JavaScript", "TypeScript", "C++", "C#",
"Go"…
How to Use pytest Fixtures and conftest.py for Shared Setup in Python
Learn how to define reusable pytest fixtures for shared setup and use them to keep tests clean and maintainable.
import pytest
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
@pytest.fixture
def calc():
return Calculator()
@pytest.fixture
def sample_numbers():
return (3, 5)
def test_add(calc, sample_numbers):
a, b = sample_numbers
assert c…
How to Validate Data with a Simple Dict-Based Rules Helper in Python
Validates a dictionary against a set of callable rules, printing pass/fail per field and returning an overall boolean.
import json
from pathlib import Path
from typing import Any, Callable
def validate_data(
data: dict[str, Any],
rules: dict[str, Callable[[Any], bool]],
path: Path | None = None,
) -> bool:
"""Validate a dict against a set of simple rules."""
all_valid = True
for field, validator in rules.item…
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"],
},
…
How to configure ruff linter rules in pyproject.toml with Python
This Python script generates a pyproject.toml file with ruff linter rules, including selected and ignored rules, per-file ignores, and complexity limits.
from pathlib import Path
def configure_ruff_rules(project_dir: str = "my_project") -> None:
"""Create a pyproject.toml with ruff linter rules for mock usage."""
pyproject_path = Path(project_dir) / "pyproject.toml"
pyproject_path.parent.mkdir(parents=True, exist_ok=True)
config = """[tool.ruff]
line-…
Lint a Dockerfile with a Mock Hadolint in Python
A lightweight Python script that simulates hadolint by scanning Dockerfile text for common lint rules and printing violations.
import subprocess
import tempfile
from pathlib import Path
def lint_dockerfile(content: str) -> list[str]:
"""Mock hadolint by checking a few rules and returning violations."""
violations = []
lines = content.splitlines()
for idx, line in enumerate(lines, start=1):
stripped = line.strip()
…
Makefile Targets for lint, test, and build in Python
This Python script defines common Makefile targets (lint, test, build) as subprocess commands, printing each target's command and executing them with error checking.
import subprocess
TARGETS = {
"lint": ["ruff", "check", "."],
"test": ["pytest", "-q"],
"build": ["python", "-m", "build"],
}
def run(target: str) -> None:
if target not in TARGETS:
raise ValueError(f"Unknown target: {target}")
print(f"Running {target}...")
subprocess.run(TARGETS[tar…
Mock pdm build and publish in Python
Simulate pdm build and publish commands with unittest.mock to test packaging workflows without triggering real builds or uploads.
from unittest.mock import Mock, patch
import pdm
def build_package() -> str:
"""Simulate building a package with pdm."""
build_mock = Mock(return_value="dist/mypackage-0.1.0-py3-none-any.whl")
with patch.object(pdm, "build", build_mock):
result = pdm.build()
return result
def publish_packa…
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.