TypedDict and NewType in Python
Typing the shape of a dict, and giving a primitive a distinct name.
from typing import NewType, NotRequired, TypedDict
StepId = NewType("StepId", int)
class StepRow(TypedDict):
tour: str
idx: int
stars: NotRequired[int]
def label(row: StepRow) -> str:
return f"{row['tour']}#{row['idx']} ({row.get('stars', 0)} stars)"
row: StepRow = {"tour": "basics", "idx": 3, "stars": 2}
print(label(row))
print(label({"tour": "traits", "idx": 0}))
print(StepId(7) + 1)
How it works
TypedDictdescribes required and optional keys.total=Falsemakes every key optional.NewTypeis a distinct type at check time, an int at run time.
Keywords and builtins used here
StepRowclassdefintlabelprintreturnstr
The run, in numbers
- Lines
- 19
- Characters to type
- 395
- Tokens
- 144
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 79 seconds.
Step 3 of 4 in Typing in depth, step 43 of 53 in Pythonic Python.