Inline references if possible when generating schema for json_schema_input_type
by Viicos · Pull Request #10439 · pydantic/pydantic (original) (raw)
Previously, the core schema for:
{ │ 'type': 'model', │ 'cls': <class '__main__.Model'>, │ 'schema': { │ │ 'type': 'model-fields', │ │ 'fields': { │ │ │ 'sub': { │ │ │ │ 'type': 'model-field', │ │ │ │ 'schema': { │ │ │ │ │ 'type': 'function-plain', │ │ │ │ │ 'function': {'type': 'no-info', 'function': <function Model. at 0x7bd0081e94e0>}, │ │ │ │ │ 'metadata': { │ │ │ │ │ │ 'pydantic_js_functions': [], │ │ │ │ │ │ 'pydantic_js_annotation_functions': [], │ │ │ │ │ │ 'pydantic_js_input_core_schema': {'type': 'definition-ref', 'schema_ref': 'main.Sub:97821927158416'} │ │ │ │ │ }, │ │ │ │ │ 'serialization': {...} │ │ │ │ }, │ │ │ │ 'metadata': {...} │ │ │ } │ │ }, │ │ 'model_name': 'Model', │ │ 'computed_fields': [] │ }, │ 'custom_init': False, │ 'root_model': False, │ 'config': {'title': 'Model'}, │ 'ref': 'main.Model:97821929019248', │ 'metadata': {...} }
With pydantic_js_input_core_schema
holding a reference to __main__.Sub:97821927158416
that would not be present in the core schema (because for a plain validator, the source type is not relevant), JSON Schema generation naturally fails (and thankfully only for JSON Schema generation, as this pydantic_js_input_core_schema
metadata field is only relevant for JSON Schemas).
My first idea was to add extra logic in the _WalkCoreSchema
class to handle this metadata field and include it in schema walking, but this is truly not ideal as we are leaking JSON Schema related logic inside this class (kind of a consequence of our metadata handling which wasn't ideal in the first place, as discussed already :/).
So I decided we should inline refs in the validator class directly, in a safe way for recursive references.
Checklist
- The pull request title is a good summary of the changes - it will be used in the changelog
- Unit tests for the changes exist
- Tests pass on CI
- Documentation reflects the changes where applicable
- My PR is ready to review, please add a comment including the phrase "please review" to assign reviewers