Skip to content

Tighten typing of msgspec.json.schema #682

Open

Description

@cfculhane

Description

First up, thanks heaps for this library, it has been immensely useful for improving the speed and safety of our application!

One feature request - we're trying to restrict Any types as mypy treats this as more or less untyped. Are you able to type the msgspec.json.schema return value to something like the below?

One caveat is that it relies on a recursive type alias, which is only enabled in newer mypy versions

T_JSON: TypeAlias = Union[Dict[str, "T_JSON"], List["T_JSON"], str, int, float, bool, None]

# Necessary as TopLevelSchema contains invalid key names when used as class\
JSONSchema = TypedDict(
    "JSONSchema",
    {
        # These keys are only really present in the top level, but having a separate top level TypedDict makes things
        # harder to type, so we'll include all keys here
        "$id": str,
        "$schema": str,
        "$defs": Mapping[str, "JSONSchema"],
        # These keys can be present at all levels
        "title": str,
        "description": str,
        "type": str,
        "properties": Mapping[str, "JSONSchema"],
        "required": Sequence[str],
        "additionalProperties": Union["JSONSchema", bool],
        "minimum": float | int,
        "maximum": float | int,
        "items": "JSONSchema",
        "enum": Sequence[str],
        "pattern": str,
        "default": T_JSON,
        "anyOf": Sequence["JSONSchema"],
        "$ref": str,  # path to a $defs
        "format": str,
    },
    total=False,
)

Might need a bit of tweaking, let me know if you like this direction and I can submit a PR!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions