Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
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.
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…
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.
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/…
How to Define Nox Sessions in Python
Automate repetitive tasks like testing and linting with reusable Nox sessions.
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")
…
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.
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…
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 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.
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…
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.
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…
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.
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:…
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 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 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.
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…
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 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 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.
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)
…
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 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 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…
Mock Python version with unittest.mock.patch
Use unittest.mock.patch to simulate a specific Python version and test version-dependent behavior.
import sys
import unittest
from unittest.mock import patch
class TestPythonVersion(unittest.TestCase):
@patch("sys.version_info", (3, 9, 0, "final", 0))
def test_python_version_pinned(self):
self.assertEqual(sys.version_info[:2], (3, 9))
print(f"Pinned version: {sys.version_info.major}.{sys.ve…
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…
Mocking loguru for Structured Logging in Python
Simulate loguru's structured logging with a custom mock that captures JSON-formatted log entries with bound context.
import json
import sys
from io import StringIO
from unittest.mock import patch
def mock_loguru():
# Simulate a structured logger with context binding
class StructuredLogger:
def __init__(self):
self.context = {}
def bind(self, **kwargs):
logger = StructuredLogger()
…
pytest mark slow skip integration
Uses pytest markers to select fast tests, skip unfinished ones, and run integration checks with verbose output.
import pytest
def test_fast():
assert 1 + 1 == 2
@pytest.mark.slow
def test_slow():
import time
time.sleep(1)
assert 5 * 5 == 25
@pytest.mark.skip(reason="Not ready for production")
def test_skipped():
assert 2 + 2 == 5
@pytest.mark.integration
def test_integration():
database = {"users": […
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.