Skip to content

Commit adc02dc

Browse files
authored
Merge pull request #27 from OpenHCSDev/hotfix/p181-choice-pairs
Expose one-pass labelled choice enumeration
2 parents f2876b9 + 688735c commit adc02dc

3 files changed

Lines changed: 23 additions & 6 deletions

File tree

‎src/python_introspect/annotation_types.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def enum_input_values(annotation: object) -> tuple[str, ...]:
179179

180180
choices = declared_annotation_choices(annotation)
181181
if choices is not None:
182-
return tuple(choices.label(choice) for choice in choices.choices())
182+
return tuple(label for label, _ in choices.labelled_choices())
183183
enum_type = declared_enum_type(annotation)
184184
if enum_type is None:
185185
return ()

‎src/python_introspect/choices.py‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,30 @@ def label(self, choice: object) -> str:
2626

2727
return str(choice)
2828

29+
def labelled_choices(self) -> tuple[tuple[str, object], ...]:
30+
"""Return each label with its value in one enumeration of the choice set."""
31+
return tuple((self.label(choice), choice) for choice in self.choices())
32+
2933
def choice_for_label(self, label: str) -> object:
3034
"""Decode one display label back to its admissible value."""
31-
32-
for choice in self.choices():
33-
if self.label(choice) == label:
35+
options = self.labelled_choices()
36+
for name, choice in options:
37+
if name == label:
3438
return choice
35-
raise ValueError(f"{label!r} is not one of {[self.label(c) for c in self.choices()]}.")
39+
raise ValueError(f"{label!r} is not one of {[name for name, _ in options]}.")
40+
41+
class LabelledChoices(AnnotationChoices):
42+
"""Choices whose source already supplies labels and values together."""
43+
44+
@abstractmethod
45+
def labelled_choices(self) -> tuple[tuple[str, object], ...]:
46+
"""Return the source's ordered label/value pairs."""
47+
48+
def choices(self) -> tuple[object, ...]:
49+
return tuple(value for _, value in self.labelled_choices())
50+
51+
def label(self, choice: object) -> str:
52+
return next(label for label, value in self.labelled_choices() if value == choice)
3653

3754

3855
def declared_annotation_choices(annotation: object) -> AnnotationChoices | None:

‎src/python_introspect/validation.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ def _(metadata: AnnotationChoices, value: object, path: str) -> None:
255255
if item not in choices:
256256
raise AnnotationValidationError(
257257
f"{path} must hold values from "
258-
f"{[metadata.label(choice) for choice in choices]}; got {item!r}."
258+
f"{[label for label, _ in metadata.labelled_choices()]}; got {item!r}."
259259
)
260260

261261

0 commit comments

Comments
 (0)