Format Data with Type Hints in Python
Build a validated person dict with modern type hints and optional list handling.
Python code
25 linesfrom 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:
raise ValueError("Invalid person data")
result: Dict[str, Any] = {
"name": name.strip().title(),
"age": age,
"is_adult": age >= 18,
}
if hobbies:
result["hobbies"] = [h.strip().lower() for h in hobbies if h.strip()]
return result
if __name__ == "__main__":
alice = format_person("alice smith", 25, ["Reading", "Cycling", " "])
bob = format_person("Bob", 12)
print("Alice:", alice)
print("Bob:", bob)
print("Type check:", isinstance(alice, dict))
Output
Alice: {'name': 'Alice Smith', 'age': 25, 'is_adult': True, 'hobbies': ['reading', 'cycling']}
Bob: {'name': 'Bob', 'age': 12, 'is_adult': False}
Type check: True
How it works
The function uses Union and Optional to explicitly declare that hobbies may be None or a list of strings. Type aliases like JsonValue make recursive data shapes readable. The if hobbies guard skips empty or None values, and the list comprehension filters out blank strings before lowercasing. Return type Dict[str, Any] signals a dictionary with string keys and values of any type, which keeps the function flexible. Running the script prints the result and confirms the object is indeed a dictionary.
Common mistakes
- Forgetting to handle `None` for optional parameters without a default
- Assuming all hobbies are non-empty without filtering blank strings
- Using `Any` everywhere instead of precise types like `Optional[List[str]]`
Variations
- Use `dataclasses` to define a `Person` class with typed fields
- Use `TypedDict` to declare the exact shape of the result dict
Real-world use cases
- Normalizing user input from a web form before storing in a database.
- Formatting API request payloads with consistent field types for downstream services.
- Building report dicts in ETL pipelines where every record must have a predictable schema.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.