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 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.
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…
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 Sort Data in Python
Sort sequences with type-safe helpers that handle mixed data with a string fallback.
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]:
"…
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.
def greet(name: str, age: int) -> str:
return f"{name} is {age} years old."
if __name__ == "__main__":
print(greet("Alice", 30))
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.
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 "…
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…
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.
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"))
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.
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…
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))
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.
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)
# …
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.