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 Use Python Type Hints for Beginners
Build a data helper module with basic type hints — Union, Optional, List, Dict, Any, and TypeVar — to make your code clearer and safer.
from typing import Any, Union, Optional, List, Dict, Tuple, Callable, TypeVar
T = TypeVar("T")
def describe(value: Any) -> str:
"""Return a human-readable description of the value's type."""
if isinstance(value, list):
return f"list of {len(value)} items"
elif isinstance(value, dict):
ret…
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…
How to use Optional type hint in Python
Use the Optional type hint to indicate a parameter can be a string or None, with an example function that handles both cases.
from typing import Optional
def greet(name: Optional[str]) -> str:
if name is None:
return "Hello, anonymous!"
else:
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Alice"))
print(greet(None))
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.