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.38k stars 72 forks source link

Support pattern for str collection types #719

Open chuckwondo opened 2 months ago

chuckwondo commented 2 months ago

Description

I have a struct field that is a collection of str (e.g., Sequence[str]) and I want to restrict each element of the collection to a pattern, but pattern is supported only for str fields, not collection types.

As a simple example, I might want my field to be annotated like so:

Annotated[
    Sequence[str],
    Meta(
        min_length=1,
        max_length=50,
        pattern="[A-Z0-9]{1,50}",
    ),
]

This corresponds to JSON Schema property type like this:

"type": "array",
"items": {
  "type": "string",
  "minLength": 1,
  "maxLength": 50,
  "pattern": "[A-Z0-9]{1,50}"
}

But msgspec produces an error like so:

TypeError: Can only set `pattern` on a str type - type `typing.Annotated[typing.Sequence[str], msgspec.Meta(pattern='[A-Z0-9]{1,50}', min_length=1, max_length=50)]` is invalid
arthurbrenno commented 2 months ago

I have the exact same issue