msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Allow `date`, `datetime`, `time` for `ge`, `gt`, `le`, `lt`

Open alexei opened this issue 2 years ago • 4 comments

Description

Currently the ge, gt, le, lt constraints are limited to ints and floats, but dates, datetimes and times are comparable as well:

now = datetime.now(timezone.utc)
yesterday = now - timedelta(days=1)
tomorrow = now + timedelta(days=1)
assert yesterday <= now <= tomorrow  # True

This would enable constraints like:

class Event(Struct):
    from_date: Annotated[datetime, msgspec.Meta(gt=...)]
    to_date: Annotated[datetime, msgspec.Meta(gt=...)]

alexei avatar Jul 13 '23 20:07 alexei

Thanks for opening this, this is definitely a feature that makes sense to add. Tossing it on the todo list.

jcrist avatar Jul 13 '23 22:07 jcrist

Out of curiosity, do these constraints need to be implemented for each type? I was looking over the list of supported types and realized decimals, strings and UUIDs can be compared as well, and just about anything that implements the comparison magic methods.

alexei avatar Jul 13 '23 23:07 alexei

Currently yes. For ints/floats a type-specific implementation can be much more efficient than a generic one.

For more complicated types like uuids/decimals/... there may be negligible benefits for implementing them in native code; we might be better served by using a generic implementation here.

jcrist avatar Jul 13 '23 23:07 jcrist