Quick Python Tip: Use typing.TypedDict for Cleaner Dict Type Hints
When working with dictionaries in Python, it's common to use the dict type hint to indicate that a function or variable expects a dictionary. However, this can lead to unclear type hints, especially when dealing with dictionaries that have a specific structure. For example, consider a dictionary that represents a user, with keys for name, email, and age.
You could use the dict[str, Any] type hint, but this doesn't provide any information about the expected keys or their corresponding value types:
from typing import Any, Dict
user: Dict[str, Any] = {'name': 'John', 'email': 'john@example.com', 'age': 30}
A better approach is to use typing.TypedDict, which allows you to define a dictionary with a specific set of keys and value types:
from typing import TypedDict
class User(TypedDict):
name: str
email: str
age: int
user: User = {'name': 'John', 'email': 'john@example.com', 'age': 30}
Using TypedDict provides several benefits, including improved IDE autocompletion, as your IDE can now suggest the expected keys and their corresponding value types.
The takeaway is that using typing.TypedDict leads to cleaner and more informative type hints, making your code easier to understand and maintain.
Follow me on Dev.to for daily Python tips and quick guides!
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
Top comments (0)