Python typeddict
"""
TypeDict allows to declare a structure that maps
the keys of a dictionary to their corresponding
data types.
Mypy would issue no error messages when applied
to the code below.
"""
from typing import TypedDict
class SalesSummary(TypedDict):
sales: int
country: str
product_codes: list[str]
def get_sales_summary() -> SalesSummary:
"""Return summary for yesterday’s sales."""
return {
"sales": 1_000,
"country": "UK",
"product_codes": ["SUYDT"],
}
# Mypy knows that sales variable is an int
# As such, it does not complain when it processes code below
sales_summary = get_sales_summary()
sales = sales_summary["sales"]
print("Sales per hour:", round(sales / 24, 2))
Wissam