jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.01k stars 59 forks source link

Tighten typing of msgspec.json.schema #682

Open cfculhane opened 1 month ago

cfculhane commented 1 month ago

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!