Skip to content

Conversation

glopesdev
Copy link

Instead of falling back to the general union case with anyOf, we represent the special case of a nullable schema using oneOf for compatibility with external tooling.

Change Summary

Following the suggestion in #7161 (comment), we propose here to replace anyOf with oneOf specifically for representing nullable schemas. This is a special case which has validation in the code to extend compatibility of Optional[T] to a large swath of tooling.

Related issue number

fix #7161

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 review @dmontagu @Viicos

Instead of falling back to the general union case with `anyOf`, we
represent the special case of a nullable schema using `oneOf` for
compatibility with external tooling.
@github-actions github-actions bot added the relnotes-fix Used for bugfixes. label Jul 26, 2025
There are a few remaining tests which may reflect complexities
highlighted in the discussion, so leaving assertions untouched for now.
Copy link

codspeed-hq bot commented Jul 26, 2025

CodSpeed Performance Report

Merging #12089 will not alter performance

Comparing glopesdev:nullable-schema-oneof (4454a9e) with main (de6528b)

Summary

✅ 46 untouched benchmarks

@Viicos
Copy link
Member

Viicos commented Aug 7, 2025

Thanks for the contribution @glopesdev. I don't think using oneOf makes sense for Pydantic. See the description of #12147 for more details.

@glopesdev
Copy link
Author

glopesdev commented Sep 2, 2025

@Viicos Thanks for pushing the development on this. The option of having type arrays to represent nullable fields of primitive types would work for us, as it works with NJsonSchema and all our current models only use primitive value types anyway.

I think there is definitely room for further discussion, and it will likely make sense to extend this feature to support other union formats. At least we now have an explicit place to further develop the functionality, since I am assuming for example if later we want to add the option for oneOf it would be done using the same parameter.

Feel free to close this PR if not appropriate anymore. It would be great to have #12147 merged into pydantic already for the next release (v1.18).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
relnotes-fix Used for bugfixes.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

JSON Schema for optional fields is incorrect.
2 participants