Skip to content

Commit 47e33a2

Browse files
trissimclaude
andcommitted
RegisteredClassChoices publishes a named enum definition in JSON schema
The field's schema is a $ref to a definition titled with the family's name, described by its docstring's first paragraph, listing the registry keys. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent be47ec8 commit 47e33a2

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎src/python_introspect/jsonable.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,12 +183,30 @@ def member(value: object) -> type:
183183

184184
return core_schema.no_info_plain_validator_function(
185185
member,
186+
ref=f"{self.family.__module__}.{self.family.__qualname__}",
186187
json_schema_input_schema=core_schema.literal_schema(
187188
[to_jsonable(choice) for choice in self.choices()]
188189
),
189190
serialization=core_schema.plain_serializer_function_ser_schema(to_jsonable),
190191
)
191192

193+
def __get_pydantic_json_schema__(self, core_schema, handler):
194+
"""Publish the family as a named string enum of its registry keys."""
195+
196+
description = (self.family.__doc__ or "").strip().split("\n\n")[0]
197+
schema = {
198+
"enum": [to_jsonable(choice) for choice in self.choices()],
199+
"title": self.family.__name__,
200+
"type": "string",
201+
}
202+
if description:
203+
schema["description"] = " ".join(description.split())
204+
reference = handler(core_schema)
205+
definition = handler.resolve_ref_schema(reference)
206+
definition.clear()
207+
definition.update(schema)
208+
return reference
209+
192210

193211
@to_jsonable.register(Enum)
194212
def _jsonable_enum(value: Enum) -> JsonValue:

‎tests/test_jsonable.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def test_registered_class_choices_validate_keys_in_pydantic():
224224
assert adapter.validate_python("square") is Square
225225
assert adapter.validate_python(Circle) is Circle
226226
assert adapter.dump_python(Square, mode="json") == "square"
227-
assert adapter.json_schema() == {"enum": ["circle", "square"], "type": "string"}
227+
assert adapter.json_schema() == {"enum": ["circle", "square"], "title": "Shape", "type": "string"}
228228
with pytest.raises(pydantic.ValidationError):
229229
adapter.validate_python("triangle")
230230
with pytest.raises(pydantic.ValidationError):

0 commit comments

Comments
 (0)