Part 15 / Topic 3 of 6
TypedDict in depth
Part 11 showed a brief TypedDict where every key is required. A JSON payload (Part 8) often has keys that are sometimes missing, and sometimes a family of dicts share most keys but not all. TypedDict has three more tools for that; it is still a plain dict when the program runs, Python never checks it, only mypy does.
Think of a form with some boxes marked "optional": the form is still just paper; only the office clerk (mypy) checks which boxes you were supposed to fill.
NotRequired: a key that may be missing
from typing import NotRequired, TypedDict
class Customer(TypedDict):
name: str
city: str
loyalty_points: NotRequired[int] # may be missing for a new customer
ravi: Customer = {"name": "Ravi", "city": "Nagpur"} # fine, no loyalty_points
print(ravi.get("loyalty_points", 0)) # 0
total=False + Required: flip the default
By default every key is required; total=False flips that so every key is optional, and Required[...] marks the few that must still be there.
from typing import Required, TypedDict
class Order(TypedDict, total=False):
order_id: Required[str]
amount: Required[float]
coupon: str # optional
order: Order = {"order_id": "ORD-102", "amount": 540.0} # fine, no coupon
One TypedDict inheriting another
class OrderBase(TypedDict):
order_id: str
amount: float
class Order(OrderBase, total=False): # order_id/amount stay required
coupon: str # new key, optional (total=False here)
Pick one style per family: either mark the few optional keys with NotRequired (most keys required), or flip with total=False and mark the few compulsory keys Required (most keys optional).
It is still a plain dict
sloppy: Customer = {"name": "Meera", "city": "Pune", "loyalty_points": "lots"} # wrong type
print(type(sloppy).__name__) # dict (Python never checked "lots" vs int)
mypy catches the wrong type; running the file does not.
| Need | Write |
|---|---|
| most keys required, a few optional | NotRequired[...] on the optional ones |
| most keys optional, a few required | TypedDict(..., total=False) + Required[...] on the required ones |
| share keys across several dict shapes | one TypedDict inheriting another |
| a real object with behaviour, not just data | a class or @dataclass (Part 9), not TypedDict |
Full program: examples/03_typed_dicts.py.
Exercise 3: Payslips with NotRequired and Required
Scenario: An HR tool's Employee dict usually has a bonus, but new joiners do not yet; a Manager dict always needs a name and basic pay, but its extra fields are optional.
What to do: Inside main():
- Write
class Employee(TypedDict):withname: str,basic_pay: float,bonus: NotRequired[float]. - Write
class Manager(Employee, total=False):that re-declaresnameandbasic_payasRequired[...], and addsteam_size: int(optional). - Write
payslip(employee: Employee) -> strreturningf"{employee['name']}: ₹{total:,.2f} (bonus ₹{bonus:,.2f})"wherebonus = employee.get("bonus", 0.0)andtotal = basic_pay + bonus. - Print
payslip(...)forAsha(basic_pay=45000.0, bonus=5000.0),Ravi(basic_pay=32000.0, no bonus), and aManagerMeera(basic_pay=68000.0, team_size=6, no bonus). - Print
"team_size" in meera, "bonus" in meera(one line, comma-separated byprint's default).
Sample output:
Asha: ₹50,000.00 (bonus ₹5,000.00)
Ravi: ₹32,000.00 (bonus ₹0.00)
Meera: ₹68,000.00 (bonus ₹0.00)
True False
💡 Hint: Manager inherits Employee's keys; re-declaring name/basic_pay as Required only matters to mypy, both already work fine at run time either way.
Show the solution to Exercise 3
"""Exercise 3: Payslips with TypedDict, NotRequired and Required.
Shows: NotRequired, total=False + Required, and TypedDict inheritance.
Run: python ex03.py (macOS/Linux: python3 ex03.py)
"""
from typing import NotRequired, Required, TypedDict
class Employee(TypedDict):
name: str
basic_pay: float
bonus: NotRequired[float]
class Manager(Employee, total=False):
name: Required[str]
basic_pay: Required[float]
team_size: int
def payslip(employee: Employee) -> str:
bonus = employee.get("bonus", 0.0)
total = employee["basic_pay"] + bonus
return f"{employee['name']}: ₹{total:,.2f} (bonus ₹{bonus:,.2f})"
def main() -> None:
asha: Employee = {"name": "Asha", "basic_pay": 45000.0, "bonus": 5000.0}
ravi: Employee = {"name": "Ravi", "basic_pay": 32000.0} # no bonus: fine
print(payslip(asha))
print(payslip(ravi))
meera: Manager = {"name": "Meera", "basic_pay": 68000.0, "team_size": 6}
print(payslip(meera))
print("team_size" in meera, "bonus" in meera)
if __name__ == "__main__":
main()