Reference library

Testing & modern typing

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

5 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 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.

type-hints typing annotations
Python
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…
13 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
Testing & modern typing easy

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.

typing optional type-hints
Python
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))
11 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.