msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Support pattern for str collection types

Open chuckwondo opened this issue 1 year ago • 1 comments

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

chuckwondo avatar Aug 15 '24 22:08 chuckwondo

I have the exact same issue

arthurbrenno avatar Aug 19 '24 12:08 arthurbrenno