Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
Dataclass with Type Hints Fields in Python
Create a data class with typed fields and default values, then instantiate and inspect it.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str = "unknown@example.com"
is_active: bool = True
if __name__ == "__main__":
person = Person(name="Alice", age=30)
print(person)
print(f"Name: {person.name}, Age: {person.age}, Email: {person.email}, A…
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…
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 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.
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…
How to use unittest mock side_effect with a sequence in Python
Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.
import unittest
from unittest.mock import Mock
class TestMockSideEffectSequence(unittest.TestCase):
def test_side_effect_sequence(self):
mock = Mock()
mock.side_effect = [1, 2, 3, Exception("boom")]
self.assertEqual(mock(), 1)
self.assertEqual(mock(), 2)
self.asser…
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.