Reference library

Testing & modern typing

pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.

4 matches
Testing & modern typing easy

Format Data with Type Hints in Python

Build a validated person dict with modern type hints and optional list handling.

type-hints typing data-formatting
Python
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:…
12 0 Open
Testing & modern typing easy

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.

filtering type-hints generics
Python
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…
11 0 Open
Testing & modern typing easy

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.

type-hints parsing typing
Python
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("}"):
     …
11 0 Open
Testing & modern typing easy

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.

pytest testing xfail
Python
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…
16 0 Open

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.