Reference library

Testing & modern typing

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

18 matches
Testing & modern typing easy

Design Data Helpers with Python TypedDict and Literal

Use TypedDict, Literal, and Union to define typed data shapes and parse values in Python.

typeddict literal union
Python
from typing import TypedDict, Literal, Optional, Union, List

class User(TypedDict):
    name: str
    age: int
    role: Literal["admin", "user", "guest"]

def describeUser(data: User) -> str:
    return f"{data['name']} ({data['age']}) — {data['role']}"

def parse_value(item: Union[int, str, None]) -> str:
    if it…
12 0 Open
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 Convert Strings to Types in Python Using TypeVar

A beginner-friendly helper that converts a string to int, float, bool, or str with type hints and graceful failure handling.

typing type-hints conversion
Python
from typing import TypeVar, Optional

T = TypeVar("T")

def convert_data(value: str, target_type: type[T]) -> Optional[T]:
    """Convert string value to target type; return None on failure."""
    try:
        if target_type is int:
            return int(value)
        elif target_type is float:
            return f…
14 0 Open
Testing & modern typing easy

How to Group Data by Key in Python with Type Hints

Group a list of dictionaries by a specified key using a typed helper function and print a summary of each group.

grouping type-hints dictionaries
Python
from typing import Any, Dict, List, TypeVar, Union

T = TypeVar("T")

def group_by(data: List[Dict[str, Any]], key: str) -> Dict[Any, List[Dict[str, Any]]]:
    """Group a list of dictionaries by a given key."""
    grouped: Dict[Any, List[Dict[str, Any]]] = {}
    for item in data:
        value = item.get(key)
     …
12 0 Open
Testing & modern typing easy

How to Merge TypedDicts in Python

Merge two TypedDict dictionaries with type-aware logic using NotRequired, **kwargs unpacking, and safe key updates.

typing typeddict dict
Python
from typing import TypedDict, NotRequired, merge  # hypothetical

class User(TypedDict):
    name: str
    email: NotRequired[str]
    age: NotRequired[int]

def merge_users(base: User, **overrides: User) -> User:
    """Merge two user dicts with typing-aware logic."""
    result: User = dict(base)
    for key, value …
13 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 Sort Data in Python

Sort sequences with type-safe helpers that handle mixed data with a string fallback.

sorting typing protocol
Python
from typing import Any, TypeVar, Protocol, Sequence, Iterable

T = TypeVar("T")
Comparable = TypeVar("Comparable", bound="Comparable")

class Sortable(Protocol):
    def __lt__(self, other: Any) -> bool: ...

S = TypeVar("S", bound=Sortable)

def sort_data(data: Sequence[S], *, reverse: bool = False) -> list[S]:
    "…
14 0 Open
Testing & modern typing easy

How to Use Basic Type Hints (int, str) for Return Values in Python

Declare a simple function with int and str type hints and a typed return value in Python.

type-hints annotations functions
Python
def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."


if __name__ == "__main__":
    print(greet("Alice", 30))
12 0 Open
Testing & modern typing easy

How to Use Literal Type Hints in Python

Use typing.Literal to restrict a function parameter to specific allowed string values and get static type checking.

typing type-hints literal
Python
from typing import Literal

def get_status_message(status: Literal["active", "inactive", "pending"]) -> str:
    """Return a message based on the status value."""
    if status == "active":
        return "Account is active"
    elif status == "inactive":
        return "Account is inactive"
    else:
        return "…
15 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 Use TypedDict and Dataclasses in Python

Create typed data structures with TypedDict and dataclasses, then use them as helper functions for describing objects in a type-safe way.

typing typdict dataclass
Python
from typing import TypedDict, NotRequired, Optional
from dataclasses import dataclass


class User(TypedDict):
    name: str
    age: NotRequired[int]
    email: Optional[str]


@dataclass
class Product:
    id: int
    title: str
    price: float = 0.0


def describe_user(user: User) -> str:
    age = user.get("age",…
12 0 Open
Testing & modern typing medium

How to Use TypedDict for Data Validation in Python

Define a TypedDict schema and validate raw dictionary input with type hints for safer, more readable data handling.

typeddict typing validation
Python
from typing import Any, Dict, List, Optional, Union, TypedDict, Literal

class Product(TypedDict):
    product_id: int
    name: str
    price: Union[int, float]
    in_stock: bool
    tags: Optional[List[str]]

def validate_product(data: Dict[str, Any]) -> Product:
    product_id: int = int(data["product_id"])
    na…
14 0 Open
Testing & modern typing easy

How to Use TypedDict for Structured Dict Typing in Python

Define and use TypedDict to add type hints to dictionaries, improving code clarity and enabling static type checking in your Python projects.

typing typeddict type-hints
Python
from typing import TypedDict


class User(TypedDict):
    name: str
    age: int
    email: str


def greet(user: User) -> str:
    return f"Hello {user['name']}, age {user['age']}, contact {user['email']}"


if __name__ == "__main__":
    alice: User = {"name": "Alice", "age": 30, "email": "alice@example.com"}
    pr…
12 0 Open
Testing & modern typing easy

How to Use Union Type Hints in Python

This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.

type-hints union typing
Python
from typing import Union

def process_value(value: Union[int, float, str]) -> str:
    if isinstance(value, (int, float)):
        return f"Number: {value * 2}"
    return f"String: {value.upper()}"

if __name__ == "__main__":
    print(process_value(10))
    print(process_value(3.14))
    print(process_value("hello"))
14 0 Open
Testing & modern typing medium

How to Validate Data in Python with Typing Hints

Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.

typing validation type-hints
Python
from typing import Any, Optional, Union, TypeVar, get_origin, get_args

T = TypeVar("T")

def validate(value: Any, expected_type: type) -> Optional[str]:
    """Returns an error message if value doesn't match expected_type, else None."""
    # Handle Optional[...] types
    origin = get_origin(expected_type)
    if or…
14 0 Open
Testing & modern typing easy

How to Validate Dataclass Fields with Python Type Hints

A beginner-friendly helper that checks if instance attributes match their declared type hints using dataclasses and get_type_hints.

dataclasses type-hints validation
Python
from typing import Any, TypeVar, get_type_hints
from dataclasses import dataclass

T = TypeVar("T")

@dataclass
class User:
    name: str
    age: int
    email: str

def validate_fields(obj: Any) -> dict[str, bool]:
    """Check if object attributes match declared type hints."""
    hints = get_type_hints(obj.__class…
13 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
Testing & modern typing easy

NamedTuple typed record in Python

Define a lightweight immutable record with type hints using typing.NamedTuple; access fields by name and unpack like a tuple.

namedtuple typing records
Python
from typing import NamedTuple


class Point(NamedTuple):
    x: float
    y: float
    label: str = "origin"


if __name__ == "__main__":
    p = Point(3.5, -2.0, "A")
    print(p)
    print(f"x={p.x}, y={p.y}, label={p.label}")
    print("is tuple:", isinstance(p, tuple))

    q = Point(1.0, 1.0)
    print(q)

    # …
14 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.