Reference library

Modern tooling

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

60 matches
Modern tooling easy

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.

validation dictionary helper
Python
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…
15 0 Open
Modern tooling easy

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.

tox ci matrix
Python
```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"],
            },
…
13 0 Open
Modern tooling easy

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.

ruff linter pyproject
Python
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-…
12 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 medium

How to set up mypy strict mode in Python

Demonstrates how to configure and run mypy in strict mode to enforce full type annotation coverage across a Python project.

mypy type-hints strict-mode
Python
from typing import Dict, Optional


def describe_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
    """Build a user description dictionary with strict type annotations."""
    user: Dict[str, object] = {"name": name, "age": age}
    if email is not None:
        user["email"] = email
    …
14 0 Open
Modern tooling easy

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.

docker linting hadolint
Python
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()
  …
14 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
Modern tooling medium

Mock Python version with unittest.mock.patch

Use unittest.mock.patch to simulate a specific Python version and test version-dependent behavior.

unittest mock version
Python
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…
13 0 Open
Modern tooling easy

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.

pdm mock unittest
Python
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…
12 0 Open
Modern tooling easy

Mock pip-compile to Resolve Requirements in Python

A mock function that mimics pip-compile by converting a requirements.in file into pinned, locked package versions.

pip-tools requirements mock
Python
import subprocess
import tempfile
from pathlib import Path


def compile_requirements_mock(requirements_in: str) -> str:
    """Mock pip-compile: resolve a simple requirements.in into a locked format."""
    lines = [line.strip() for line in requirements_in.splitlines() if line.strip() and not line.startswith("#")]
  …
12 0 Open
Modern tooling medium

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.

loguru logging mock
Python
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()
  …
12 0 Open
Modern tooling easy

pytest mark slow skip integration

Uses pytest markers to select fast tests, skip unfinished ones, and run integration checks with verbose output.

pytest markers testing
Python
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": […
17 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.