Skip to content

Support of extra and not required arguments for TypedDict in JSON schema generator #641

@tokarenko

Description

@tokarenko

I am tring to generate JSON schema for TypedDict allowing for extra/optional arguments. With NotRequired typing I get the following error:

from typing import TypedDict
from apischema.json_schema import deserialization_schema

class MyTypedDict(TypedDict):
    my_key1: Optional[int]
    my_key2: NotRequired[int]

deserialization_schema(MyTypedDict)
>>> TypeError: NotRequired accepts only a single type. Got (<class 'int'>,).

Workaround with total=False seems to work but I expect additionalProperties to be True instead of False.

from typing import TypedDict, List
from apischema.json_schema import deserialization_schema

class MyTypedDict(TypedDict, total=False):
    a: str
    b: str

deserialization_schema(MyTypedDict)
>>> {'type': 'object', 'properties': {'a': {'type': 'string'}, 'b': {'type': 'string'}}, 'additionalProperties': False, '$schema': 'http://json-schema.org/draft/2020-12/schema#'}

I suggest the following:

  1. Add support for PEP 728 closed class parameter as a way to enable "additionalProperties": true in JSON schema for TypedDict.
  2. Set "additionalProperties": true by default for TypedDict as the PEP states:

Passing closed=False explicitly requests the default TypedDict behavior, where arbitrary other keys may be present ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions