Expose ability to use a callable as the discriminator in a tagged union #6915
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Still needs documentation, but I wanted to open this and get feedback.
(I started working on this because of #6040, where I noticed some errors that could maybe be cleaned up by this. But I've been thinking about it for a while, and there have been other cases where it was even more well-suited.)
As demonstrated by the tests, this can improve errors for many cases today, especially those involving recursive types with unions in the recursion.
I have not made
Field(discriminator=CallableDiscriminator(...))
work, mostly because the current logic for applying discriminators fromField
is pretty nested/complex and doesn't have access to theGenerateSchema
instance, but I also think it can be partially justified as — theField
discriminator affects JSON schema, whereas theCallableDiscriminator
annotation won't affect the JSON schema.Alternatively, I think it could be justified as an initial implementation, and if it gets traction and people like it, we could make it work in
Field(...)
in the future. (Or, if necessary, we could just get that implemented, I just wanted to keep the changes smaller if possible.)Selected Reviewer: @Kludex