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 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 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 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 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 Use prompt_toolkit Autocomplete in Python
Demonstrates an interactive command-line prompt with autocomplete using prompt_toolkit's WordCompleter and a mock dataset.
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
def main():
"""Demo of prompt_toolkit autocomplete with a mock dataset."""
# A simple mock "database" of programming languages
languages = [
"Python", "Java", "JavaScript", "TypeScript", "C++", "C#",
"Go"…
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…
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.
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…
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.
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
…
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.