Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
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.
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…
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 Load and Inspect CSV Data with a Dataclass Helper in Python
This code defines a DataHelper dataclass that reads a CSV file into a list of dictionaries and prints basic dataset information.
from pathlib import Path
from dataclasses import dataclass
from typing import Any
@dataclass
class DataHelper:
"""Simple helper for loading and inspecting CSV data."""
filepath: Path
def load_csv(self, *, delimiter: str = ",") -> list[dict[str, Any]]:
"""Read CSV into a list of dictionaries."""
…
How to Load and Save CSV and JSON Files in Python
A beginner-friendly data helper that loads or saves CSV and JSON files using only the Python standard library, with automatic format detection from the file extension.
from pathlib import Path
import json
import csv
def load_data(file_path):
"""Load CSV or JSON data from disk based on file extension."""
path = Path(file_path)
if path.suffix == ".json":
with path.open() as f:
return json.load(f)
elif path.suffix == ".csv":
with path.open(…
How to Mock a semantic-release Changelog in Python
This Python code simulates a semantic-release changelog generator, grouping commits by type and formatting them into a markdown changelog.
import json
from datetime import datetime
class SemanticReleaseChangelog:
def __init__(self, version, commits):
self.version = version
self.commits = commits
self.release_date = datetime.now().isoformat()
def generate_changelog(self):
grouped = {}
for commit in self.c…
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)
…
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()
…
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.