Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Design Data Helpers with Python TypedDict and Literal
Use TypedDict, Literal, and Union to define typed data shapes and parse values in 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…
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 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.
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)
…
How to Merge TypedDicts in Python
Merge two TypedDict dictionaries with type-aware logic using NotRequired, **kwargs unpacking, and safe key updates.
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 …
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 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 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.
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",…
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.
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…
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.