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.3k stars 67 forks source link

IntEnum/IntFlag not considered as numeric types for msgspec.Meta #587

Open mikeshardmind opened 10 months ago

mikeshardmind commented 10 months ago

Description

This seems related to #487 , but I came across a slightly different case of it.

import enum
from msgspec import msgpack, Struct, Meta

class SomeEnum(enum.IntFlag, boundary=enum.STRICT):
    empty = 0
    a = 1
    b = 2
    c = 4

class SomeStruct(Struct, array_like=True):
    x: Annotated[SomeEnum, Meta(lt=2)] = SomeEnum.empty
    ...

This was done in an initial attempt to work around the inability to specify this with Literal[SomeEnum.empty, SomeEnum.a] in a situation where only that subset of the enum is valid for that particular field to ship something now, then add more info to the related issue.

TypeError: Can only set `lt` on a numeric type

I've left the original names and module names out as irrelevant, but it would seem that IntEnums should be considered numeric types for the constraints addable with Meta

jcrist commented 10 months ago

Apologies for the delayed response here. In the long run I intend to support generic bound constraints, so something like this should work. But beyond a workaround for #487, can you think of a use case for </> constraints for IntEnum types?

mikeshardmind commented 10 months ago

Outside of as a workaround for #487, probably not. IntEnums already come with boundary checks (even included in the example there) for internal to the enum situations. I'd probably avoid forbidding it unless it adds to the costs involved somewhere you think needs considering (either for you on maintaining, performance for those not using it, etc.) so that it could be transparently mostly compatible with integers; However, I can't say that I have or see a motivating case beyond less surprising behavior.