Reference library

Modern tooling

uv, ruff, pyproject.toml, packaging, and current Python project workflows.

28 matches
Modern tooling medium

How to Bind and Mock structlog Context in Python

Shows how to bind persistent key-value context to a structlog logger, unbind keys, and mock the logger in tests to verify context is passed correctly.

structlog logging mocking
Python
import structlog
from unittest.mock import patch

logger = structlog.get_logger()

def demo():
    logger = structlog.get_logger()
    logger = logger.bind(user_id=42, request_id="abc123")
    logger.info("user logged in", action="login")
    
    # Unbind a key
    logger = logger.unbind("user_id")
    logger.info("r…
18 0 Open
Modern tooling easy

How to Create a Mock Virtualenv with an Activation Script in Python

Create a mock virtualenv directory with a generated bash activation script using Python's standard library.

virtualenv mock subprocess
Python
import os
import subprocess
import sys
from pathlib import Path


def mock_virtualenv(name: str = "myenv") -> Path:
    """Create a mock virtualenv directory and activation script."""
    env_dir = Path(name)
    env_dir.mkdir(exist_ok=True)
    (env_dir / "bin").mkdir(exist_ok=True)

    activate_script = f"""#!/bin/…
13 0 Open
Modern tooling easy

How to Define Nox Sessions in Python

Automate repetitive tasks like testing and linting with reusable Nox sessions.

nox automation task-runner
Python
import nox


@nox.session(python=["3.9", "3.10"])
def tests(session):
    session.install("pytest")
    session.run("pytest")


@nox.session(python="3.9")
def lint(session):
    session.install("ruff")
    session.run("ruff", "check", ".")


if __name__ == "__main__":
    print("Nox sessions defined: tests, lint")
   …
13 0 Open
Modern tooling easy

How to Generate a Mock Rollbar Error Report in Python

Create a realistic fake Rollbar error report with random timestamps, levels, messages, and counts for testing and demos.

rollbar mock-data error-reporting
Python
import json
import random
import time
from datetime import datetime, timedelta


def mock_rollbar_report(n_errors=5):
    messages = [
        "TypeError: unsupported operand type(s) for +: 'int' and 'str'",
        "KeyError: 'user_id'",
        "ValueError: invalid literal for int() with base 10: 'abc'",
        "At…
13 0 Open
Modern tooling easy

How to Initialize Sentry SDK with a Mock DSN in Python

Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.

sentry sdk dsn
Python
import sentry_sdk

# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
    dsn="https://mock-public@mock-host/mock-project",
    traces_sample_rate=1.0,
    environment="development",
)

# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
13 0 Open
Modern tooling easy

How to Mock BugSnag Notify in Python

Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.

mocking bugsnag testing
Python
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…
16 0 Open
Modern tooling medium

How to Mock CLI Output in Typer with unittest.mock

Mock and capture Typer CLI output using unittest.mock.patch and io.StringIO for testing command-line applications.

typer cli testing
Python
import typer
from unittest.mock import patch
import io

app = typer.Typer()

@app.command()
def greet(name: str, age: int = 18, uppercase: bool = False):
    """Greet a person with optional formatting."""
    message = f"Hello {name}, age {age}"
    if uppercase:
        message = message.upper()
    typer.echo(messag…
11 0 Open
Modern tooling easy

How to Mock Click CLI App Subcommands in Python

Simulate Click-style CLI subcommand calls in Python by using argparse with subparsers and mocking sys.argv in tests or scripts.

cli argparse mocking
Python
import sys
import argparse


def do_greet(args):
    print(f"Hello, {args.name}!")


def do_goodbye(args):
    print(f"Goodbye, {args.name}!")


def main():
    parser = argparse.ArgumentParser(prog="clickapp")
    subparsers = parser.add_subparsers(dest="command", required=True)

    greet_parser = subparsers.add_par…
14 0 Open
Modern tooling easy

How to Mock Commitizen Version Bump in Python

Simulate commitizen's version bump logic and mock the subprocess call to avoid real execution in tests.

commitizen mock subprocess
Python
import subprocess
from unittest.mock import patch, MagicMock


def bump_version(current_version: str, increment: str = "patch") -> str:
    """Simulate commitizen's version bump logic."""
    major, minor, patch = map(int, current_version.split("."))
    if increment == "major":
        major += 1
        minor = 0
  …
15 0 Open
Modern tooling easy

How to Mock Fabric Connections in Python for Task Testing

Create a lightweight MockConnection class to replace fabric.Connection and test task functions without SSH.

fabric mocking testing
Python
from fabric import Connection


class MockConnection:
    """Minimal mock of fabric.Connection for task testing."""

    def __init__(self):
        self.commands = []

    def run(self, command, **kwargs):
        self.commands.append(command)
        return f"OK: {command}"


def deploy(conn):
    """Deploy the app:…
14 0 Open
Modern tooling easy

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.

opentelemetry testing tracing
Python
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…
13 0 Open
Modern tooling easy

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.

twine testpypi mock
Python
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")):
…
12 0 Open
Modern tooling easy

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.

uv mocking pip
Python
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…
14 0 Open
Modern tooling medium

How to Mock a PEP 517 Build Backend in Python

Use unittest.mock.Mock to simulate a PEP 517 backend interface, stub build hooks, and verify calls for package build automation.

pep517 unittest.mock packaging
Python
import json
from unittest.mock import Mock

# Simulate a PEP 517 backend interface
class Pep517Backend:
    def build_wheel(self, wheel_directory, config_settings=None, metadata_directory=None):
        return f"{wheel_directory}/mock_package-1.0.0-py3-none-any.whl"

    def get_requires_for_build_wheel(self, config_s…
14 0 Open
Modern tooling easy

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.

pyenv pathlib version-control
Python
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…
12 0 Open
Modern tooling easy

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.

isort import-sorting mock
Python
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__":
   …
10 0 Open
Modern tooling easy

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.

setuptools-scm mock unittest
Python
```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…
14 0 Open
Modern tooling medium

How to Mock subprocess.run for Black Formatter in Python

Use unittest.mock to simulate subprocess.run calls in a Python function that runs the Black formatter, allowing isolated testing without executing external commands.

unittest mock subprocess
Python
import subprocess
from unittest.mock import Mock, patch

def run_black_formatter(file_path: str, check_only: bool = False) -> dict:
    """Run black formatter on a file via subprocess."""
    cmd = ["black", "--check" if check_only else "-", file_path]
    result = subprocess.run(cmd, capture_output=True, text=True)
 …
15 0 Open
Modern tooling easy

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.

pytest parametrize testing
Python
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 _…
15 0 Open
Modern tooling easy

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.

vscode settings json
Python
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…
13 0 Open
Modern tooling easy

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.

coverage testing unittest
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…
12 0 Open
Modern tooling easy

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.

pytest fixtures conftest
Python
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…
13 0 Open
Modern tooling medium

How to mock argparse nested subparsers in Python

Build an argparse parser with nested subparsers and test it using unittest.mock.patch for sys.argv and sys.stdout.

argparse subparsers unittest
Python
import argparse
from unittest.mock import patch
from io import StringIO

def build_parser():
    parser = argparse.ArgumentParser(prog="app")
    subparsers = parser.add_subparsers(dest="command", required=True)

    # Outer subparser
    outer = subparsers.add_parser("outer")
    outer_sub = outer.add_subparsers(dest…
15 0 Open
Modern tooling easy

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.

subprocess makefile tooling
Python
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…
14 0 Open

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.