Format Data with Type Hints in Python

Build a validated person dict with modern type hints and optional list handling.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 12 views 0 copies

Python code

25 lines
Python 3.9+
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:
        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

stdout
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

  1. Use `dataclasses` to define a `Person` class with typed fields
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.