Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Format Data with Type Hints in Python
Build a validated person dict with modern type hints and optional list handling.
from typing import Any, Dict, List, Optional, Union
JsonValue = Union[str, int, float, bool, None, List["JsonValue"], Dict[str, "JsonValue"]]
def format_person(name: str, age: int, hobbies: Optional[List[str]] = None) -> Dict[str, Any]:
"""Build a person dict with validated typing."""
if not name or age < 0:…
How to Filter Data in Python with Type Hints
A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.
from typing import Iterable, TypeVar, Callable, Any
T = TypeVar("T")
def filter_data(
items: Iterable[T],
predicate: Callable[[T], bool] | None = None,
*,
min_value: float | None = None,
max_value: float | None = None,
) -> list[T]:
"""Filter items by predicate and/or numeric bounds."""
r…
How to Parse Data with Type Hints in Python
A beginner-friendly helper that parses simple dictionary- or list-like strings into typed Python structures using modern typing annotations.
from typing import Any, Dict, List, Union
def parse_data(raw: str) -> Union[Dict[str, Any], List[Any], str]:
"""Parse a simple string into structured data using type hints."""
cleaned = raw.strip()
if not cleaned:
return {}
if cleaned.startswith("{") and cleaned.endswith("}"):
…
How to mark known bugs with pytest xfail in Python
Use @pytest.mark.xfail to mark tests that are expected to fail due to known bugs, with optional strict mode to control pass/fail behavior.
import pytest
def divide(a: int, b: int) -> float:
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
@pytest.mark.xfail(reason="Known bug: division returns int instead of float", strict=False)
def test_divide_integer_division():
result = divide(10, 4)
assert isinstanc…
Browse by section
Each section groups closely related Python snippets.
Testing & modern typing — Python code examples
What you will find here
This page collects testing & modern typing 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.