Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
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.
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…
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.
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,
…
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.
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."""
…
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 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 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 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…
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.
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("#")]
…
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.