A simple typed namespace. At runtime it is equivalent to a plain dict. TypedDict creates a dictionary type such that a type checker will expect all instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checke
(typename, fields=_sentinel, /, *, total=True)
| 3271 | |
| 3272 | |
| 3273 | def TypedDict(typename, fields=_sentinel, /, *, total=True): |
| 3274 | """A simple typed namespace. At runtime it is equivalent to a plain dict. |
| 3275 | |
| 3276 | TypedDict creates a dictionary type such that a type checker will expect all |
| 3277 | instances to have a certain set of keys, where each key is |
| 3278 | associated with a value of a consistent type. This expectation |
| 3279 | is not checked at runtime. |
| 3280 | |
| 3281 | Usage:: |
| 3282 | |
| 3283 | >>> class Point2D(TypedDict): |
| 3284 | ... x: int |
| 3285 | ... y: int |
| 3286 | ... label: str |
| 3287 | ... |
| 3288 | >>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK |
| 3289 | >>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check |
| 3290 | >>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') |
| 3291 | True |
| 3292 | |
| 3293 | The type info can be accessed via the Point2D.__annotations__ dict, and |
| 3294 | the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. |
| 3295 | TypedDict supports an additional equivalent form:: |
| 3296 | |
| 3297 | Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) |
| 3298 | |
| 3299 | By default, all keys must be present in a TypedDict. It is possible |
| 3300 | to override this by specifying totality:: |
| 3301 | |
| 3302 | class Point2D(TypedDict, total=False): |
| 3303 | x: int |
| 3304 | y: int |
| 3305 | |
| 3306 | This means that a Point2D TypedDict can have any of the keys omitted. A type |
| 3307 | checker is only expected to support a literal False or True as the value of |
| 3308 | the total argument. True is the default, and makes all items defined in the |
| 3309 | class body be required. |
| 3310 | |
| 3311 | The Required and NotRequired special forms can also be used to mark |
| 3312 | individual keys as being required or not required:: |
| 3313 | |
| 3314 | class Point2D(TypedDict): |
| 3315 | x: int # the "x" key must always be present (Required is the default) |
| 3316 | y: NotRequired[int] # the "y" key can be omitted |
| 3317 | |
| 3318 | See PEP 655 for more details on Required and NotRequired. |
| 3319 | |
| 3320 | The ReadOnly special form can be used |
| 3321 | to mark individual keys as immutable for type checkers:: |
| 3322 | |
| 3323 | class DatabaseUser(TypedDict): |
| 3324 | id: ReadOnly[int] # the "id" key must not be modified |
| 3325 | username: str # the "username" key can be changed |
| 3326 | |
| 3327 | """ |
| 3328 | if fields is _sentinel or fields is None: |
| 3329 | import warnings |
| 3330 |