msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Please consider not restricting `Union` to one type.

Open wikiped opened this issue 1 year ago • 1 comments

Description

Suppose that an int field needs to be bound to some intervals:

from typing import Annotated
import msgspec as ms


LowerBounds = Annotated[int, ms.Meta(ge=-10, le=-1)]
UpperBounds = Annotated[int, ms.Meta(ge=1, le=10)]


class T(ms.Struct):
    n: LowerBounds | UpperBounds
    

As the docs state:

Unions may contain at most one type that encodes to an integer (int, enum.IntEnum)

the following will then expectedly fail:

ms.json.decode('{"n":-1}', type=T)
# msgspec.ValidationError: Expected `int` >= 1 - at `$.n`

Please consider lifting this restriction.

wikiped avatar Nov 07 '23 07:11 wikiped

I too require this feature for the following data type:

class Ok(Generic[A]):
    def __init__(self, value: A):
        self.value = value

    def to_json(self) -> JSON:
        return {"ok": self.value}

    def __bool__(self):
        return True


class Err(Generic[A]):
    def __init__(self, value: A):
        self.value = value

    def to_json(self) -> JSON:
        return {"err": self.value}

    def __bool__(self):
        return False


Result = Ok[A] | Err[B]

aspizu avatar Nov 11 '23 18:11 aspizu