Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please consider not restricting Union to one type. #582

Open
wikiped opened this issue Nov 7, 2023 · 1 comment
Open

Please consider not restricting Union to one type. #582

wikiped opened this issue Nov 7, 2023 · 1 comment

Comments

@wikiped
Copy link

wikiped commented Nov 7, 2023

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.

@aspizu
Copy link

aspizu commented Nov 11, 2023

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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants