DEV Community

qing
qing

Posted on • Edited on

Quick Python Tip: Use typing.TypedDict for Cleaner Dict Type Hints

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 and uninformative type hints, especially when dealing with complex dictionaries.

For example, consider a dictionary with the following structure:

from typing import Any, TypedDict

# Plain dict type hint
user_data: dict[str, Any] = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john@example.com'
}
Enter fullscreen mode Exit fullscreen mode

With a plain dict[str, Any] type hint, it's unclear what keys and values the dictionary is expected to contain.

In contrast, using typing.TypedDict provides a more explicit and self-documenting way to define dictionary types:

class UserData(TypedDict):
    name: str
    age: int
    email: str

user_data: UserData = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john@example.com'
}
Enter fullscreen mode Exit fullscreen mode

By using TypedDict, you get better IDE autocompletion, as the IDE can provide suggestions based on the explicitly defined keys and types.
This leads to a one-sentence takeaway: Using typing.TypedDict provides cleaner and more informative dictionary type hints, resulting in better code readability and maintainability.


Follow me on Dev.to for daily Python tips and quick guides!


喜欢这篇文章?关注获取更多Python自动化内容!


If you found this useful, you might like Python Automation Scripts Pack (10 Ready-to-Use Tools) — a practical resource that takes things a step further. At $14.99 it's a solid investment for your toolkit.

Top comments (0)