Reference library

Modern tooling

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

10 matches
Modern tooling easy

Data Conversion Helper Functions in Python

A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.

json datetime pathlib
Python
from datetime import datetime
from pathlib import Path
import json

def to_json(data, indent=2):
    """Convert Python data to pretty-printed JSON string."""
    return json.dumps(data, indent=indent, default=str)

def from_json(json_string):
    """Parse JSON string back into Python data."""
    return json.loads(jso…
12 0 Open
Modern tooling medium

How to Enforce Indentation Rules From .editorconfig in Python

A mock function that reads .editorconfig-style indentation rules (spaces or tabs, size) and fixes indentation in source code lines by tracking brace depth.

editorconfig indentation formatting
Python
def enforce_indent(editorconfig_rules, file_content):
    """
    Mock function to enforce indentation rules from .editorconfig.
    Returns the content with indentation fixed (or unchanged if already compliant).
    """
    indent_style = editorconfig_rules.get("indent_style", "spaces")
    indent_size = int(editorco…
14 0 Open
Modern tooling easy

How to Export a Conda Environment YAML File in Python

Generate a mock conda environment YAML export with a reusable Python function and the PyYAML library.

conda yaml environment
Python
import yaml


def conda_env_mock(name="demo_env", channels=None, packages=None):
    channels = channels or ["defaults"]
    packages = packages or [
        "python=3.11",
        "pip",
        "numpy=1.24.3",
        "pandas=2.0.3",
    ]
    env_dict = {
        "name": name,
        "channels": channels,
        …
17 0 Open
Modern tooling easy

How to Format Data with Python's datetime and JSON Helpers

A beginner-friendly set of helper functions to format dates and safely read/write JSON files in Python.

datetime json files
Python
from datetime import datetime
from pathlib import Path
import json


def format_today(pattern: str = "%Y-%m-%d") -> str:
    """Return today's date formatted with the given pattern."""
    return datetime.now().strftime(pattern)


def load_json(file_path: str) -> dict:
    """Read and parse a JSON file safely."""
    …
12 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 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 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 Type Check a Mock with pyright in Python

Shows how pyright validates a mock function against a TypedDict and Callable signature before runtime.

pyright type-checking mocking
Python
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…
15 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

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.