msgspec
msgspec copied to clipboard
Allow `date`, `datetime`, `time` for `ge`, `gt`, `le`, `lt`
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=...)]
Thanks for opening this, this is definitely a feature that makes sense to add. Tossing it on the todo list.
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.
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.