Skip to content

Commit fdb2f17

Browse files
trissimclaude
andcommitted
Add AnnotationChoices: finite choice sets declared as Annotated metadata
Validation checks values (and sequence items) against the declared choices and validates type[X] annotations by subclass; enum_input_values and declared_annotation_choices expose the choices to form builders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 83c1efe commit fdb2f17

5 files changed

Lines changed: 170 additions & 1 deletion

File tree

‎src/python_introspect/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
is_enableable,
4040
mark_enableable,
4141
)
42+
from .choices import AnnotationChoices, declared_annotation_choices
4243
from .validation import (
4344
AnnotatedDataclassValidationMixin,
4445
AnnotationValidationError,
@@ -106,6 +107,8 @@
106107
"overlay_non_none_dataclass",
107108
"validate_annotated_dataclass",
108109
"validate_annotation_value",
110+
"AnnotationChoices",
111+
"declared_annotation_choices",
109112
# Dataclass projection
110113
"dataclass_from_mapping",
111114
"project_dataclass",

‎src/python_introspect/annotation_types.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,9 +143,16 @@ def enum_input_values(annotation: object) -> tuple[str, ...]:
143143
144144
String-valued members expose their value. Members whose values are not
145145
strings expose their name, which keeps JSON and command-line projections
146-
unambiguous, including enums whose concrete value is ``None``.
146+
unambiguous, including enums whose concrete value is ``None``. A field
147+
declaring :class:`~python_introspect.choices.AnnotationChoices` exposes its
148+
choice labels.
147149
"""
148150

151+
from .choices import declared_annotation_choices
152+
153+
choices = declared_annotation_choices(annotation)
154+
if choices is not None:
155+
return tuple(choices.label(choice) for choice in choices.choices())
149156
enum_type = declared_enum_type(annotation)
150157
if enum_type is None:
151158
return ()

‎src/python_introspect/choices.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""Finite value sets declared as ``Annotated`` metadata."""
2+
3+
from __future__ import annotations
4+
5+
from abc import ABC, abstractmethod
6+
from typing import Annotated, get_args, get_origin
7+
8+
from .annotation_types import is_union_type
9+
10+
11+
class AnnotationChoices(ABC):
12+
"""``Annotated`` metadata declaring the finite values a field may hold.
13+
14+
The declaring package owns the choice set, which may be computed when it is
15+
asked for. Validation checks each value (or each item of a sequence value)
16+
against it, and form builders render the choices with their labels.
17+
``None`` is never a choice: an ``Optional`` annotation admits it separately.
18+
"""
19+
20+
@abstractmethod
21+
def choices(self) -> tuple[object, ...]:
22+
"""Return the admissible values in display order."""
23+
24+
def label(self, choice: object) -> str:
25+
"""Return the display label for one admissible value."""
26+
27+
return str(choice)
28+
29+
def choice_for_label(self, label: str) -> object:
30+
"""Decode one display label back to its admissible value."""
31+
32+
for choice in self.choices():
33+
if self.label(choice) == label:
34+
return choice
35+
raise ValueError(f"{label!r} is not one of {[self.label(c) for c in self.choices()]}.")
36+
37+
38+
def declared_annotation_choices(annotation: object) -> AnnotationChoices | None:
39+
"""Return the choice set declared on an annotation.
40+
41+
The metadata is found through ``Annotated``, ``Optional`` and homogeneous
42+
containers, mirroring how enum declarations are recognised.
43+
"""
44+
45+
if get_origin(annotation) is Annotated:
46+
base, *metadata = get_args(annotation)
47+
for item in metadata:
48+
if isinstance(item, AnnotationChoices):
49+
return item
50+
return declared_annotation_choices(base)
51+
members = get_args(annotation)
52+
if is_union_type(annotation):
53+
found = [
54+
choices
55+
for member in members
56+
if member is not type(None)
57+
if (choices := declared_annotation_choices(member)) is not None
58+
]
59+
return found[0] if len(found) == 1 else None
60+
origin = get_origin(annotation)
61+
if origin in {list, set, frozenset} and len(members) == 1:
62+
return declared_annotation_choices(members[0])
63+
if origin is tuple and len(members) == 2 and members[1] is Ellipsis:
64+
return declared_annotation_choices(members[0])
65+
return None

‎src/python_introspect/validation.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from annotated_types import Ge, Gt, Interval, Le, Len, Lt, MaxLen, MinLen, Predicate
2020

2121
from .annotation_types import is_union_type, resolved_class_annotations
22+
from .choices import AnnotationChoices
2223

2324

2425
class AnnotationValidationError(ValueError):
@@ -146,6 +147,9 @@ def validate_annotation_value(
146147
if origin in {dict, Mapping}:
147148
_validate_mapping(annotation, value, path)
148149
return
150+
if origin is type:
151+
_validate_class_value(annotation, value, path)
152+
return
149153
if origin is Callable:
150154
if not callable(value):
151155
raise TypeError(f"{path} must be callable; got {type(value).__name__}.")
@@ -205,6 +209,21 @@ def _validate_sequence(annotation: object, value: object, path: str) -> None:
205209
validate_annotation_value(members[0], item, path=f"{path}[{index}]")
206210

207211

212+
def _validate_class_value(annotation: object, value: object, path: str) -> None:
213+
if not isinstance(value, type):
214+
raise TypeError(f"{path} must be a class; got {type(value).__name__}.")
215+
members = get_args(annotation)
216+
if not members or members[0] is Any:
217+
return
218+
bounds = get_args(members[0]) if is_union_type(members[0]) else (members[0],)
219+
if not any(isinstance(bound, type) and issubclass(value, bound) for bound in bounds):
220+
raise TypeError(
221+
f"{path} must be a subclass of "
222+
f"{' | '.join(_annotation_label(bound) for bound in bounds)}; "
223+
f"got {value.__qualname__}."
224+
)
225+
226+
208227
def _validate_mapping(annotation: object, value: object, path: str) -> None:
209228
if not isinstance(value, Mapping):
210229
raise TypeError(f"{path} must be a mapping; got {type(value).__name__}.")
@@ -226,6 +245,20 @@ def _validate_constraint(metadata: object, value: object, path: str) -> None:
226245
"""Ignore annotation metadata that does not declare a runtime constraint."""
227246

228247

248+
@_validate_constraint.register
249+
def _(metadata: AnnotationChoices, value: object, path: str) -> None:
250+
if value is None:
251+
return
252+
choices = metadata.choices()
253+
items = value if isinstance(value, (list, tuple, frozenset, set)) else (value,)
254+
for item in items:
255+
if item not in choices:
256+
raise AnnotationValidationError(
257+
f"{path} must hold values from "
258+
f"{[metadata.label(choice) for choice in choices]}; got {item!r}."
259+
)
260+
261+
229262
@_validate_constraint.register
230263
def _(metadata: Ge, value: object, path: str) -> None:
231264
if value < metadata.ge:

‎tests/test_annotation_choices.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from dataclasses import dataclass, field
2+
from typing import Annotated, Optional
3+
4+
import pytest
5+
6+
from python_introspect import (
7+
AnnotatedDataclassValidationMixin,
8+
AnnotationChoices,
9+
AnnotationValidationError,
10+
declared_annotation_choices,
11+
enum_input_values,
12+
)
13+
14+
15+
class _Kind:
16+
pass
17+
18+
19+
class _Alpha(_Kind):
20+
pass
21+
22+
23+
class _Beta(_Kind):
24+
pass
25+
26+
27+
class _Other:
28+
pass
29+
30+
31+
class _KindChoices(AnnotationChoices):
32+
def choices(self):
33+
return (_Alpha, _Beta)
34+
35+
def label(self, choice):
36+
return choice.__name__.strip("_").lower()
37+
38+
39+
_CHOICES = _KindChoices()
40+
41+
42+
@dataclass(frozen=True)
43+
class _Declared(AnnotatedDataclassValidationMixin):
44+
kind: Annotated[Optional[type[_Kind]], _CHOICES] = None
45+
kinds: Annotated[list[type[_Kind]], _CHOICES] = field(default_factory=list)
46+
47+
48+
def test_choices_are_found_through_optional_and_containers():
49+
assert declared_annotation_choices(Optional[Annotated[list[type[_Kind]], _CHOICES]]) is _CHOICES
50+
assert declared_annotation_choices(Annotated[Optional[type[_Kind]], _CHOICES]) is _CHOICES
51+
assert declared_annotation_choices(list[int]) is None
52+
assert enum_input_values(Annotated[list[type[_Kind]], _CHOICES]) == ("alpha", "beta")
53+
assert _CHOICES.choice_for_label("beta") is _Beta
54+
55+
56+
def test_validation_admits_only_declared_choices_and_class_bounds():
57+
_Declared(kind=_Alpha, kinds=[_Beta])
58+
with pytest.raises(AnnotationValidationError):
59+
_Declared(kinds=[_Kind])
60+
with pytest.raises(TypeError):
61+
_Declared(kind=_Other)

0 commit comments

Comments
 (0)