Support constraints on Optional (union with None) types#994
Support constraints on Optional (union with None) types#994Siyet wants to merge 1 commit intojcrist:mainfrom
Conversation
Derive constraint_kind from non-None union members so that Annotated[X | None, Meta(...)] constraints are validated correctly. Previously any constraint on an Optional[X] type raised TypeError because the union branch left kind as CK_OTHER. Closes #804
|
CI failures are unrelated to this change: "Profile Windows (ARM64)" - runner infra issue ("Install command runner" step) |
|
Resolved in the community fork msgspec-arise: PR #10, released in v0.20.2. |
|
Not supporting this was intentional. We only support applying annotations directly to the type they apply to for clarity. Since |
Summary
constraint_kindfrom non-None union members so thatAnnotated[X | None, Meta(...)]constraints are validated correctlyOptional[X]type raisedTypeErrorbecause the union branch leftkindasCK_OTHERCloses #804
Test plan
All 275 constraint tests pass (Ubuntu 22.04, Python 3.10):
New tests added:
test_optional_str_min_length-Annotated[Union[str, None], Meta(min_length=3)]test_optional_int_gt-Annotated[Union[int, None], Meta(gt=0)]test_optional_float_ge-Annotated[Union[float, None], Meta(ge=0.0)]Each test verifies:
Nonevalues pass through without constraint checksValid values are accepted
Invalid values raise
ValidationErrorCI passes on all platforms