Refactor discriminated unions to ensure references to original discriminator are preserved #794
Replies: 5 comments 2 replies
-
After some experimentation, this seems to be the code we need to wrap around: Pet = create_model("Pet", root=(Annotated[Union[Cat, Dog], Field(discriminator='pet_type')], ...), __base__=RootModel) This would make it trivial to go from the current implementation to this one with a single function applied on top of each discriminator. |
Beta Was this translation helpful? Give feedback.
-
@bruno-f-cruz is there a specific instance where the same union is being repeated that you are looking to improve? |
Beta Was this translation helpful? Give feedback.
-
A pydantic maintainer has recently provided an alternative pattern that seems to address this issue with a more succinct syntax. I might tackle it in the Behavior.Services repository at some point but for now I will just leave it here as reference AllenNeuralDynamics/Aind.Behavior.Services#114 |
Beta Was this translation helpful? Give feedback.
-
Here is a link to the issue Bruno is referring to: pydantic/pydantic#10635 (comment) I wonder how it de-serializes json? |
Beta Was this translation helpful? Give feedback.
-
Consider the following example:
Pet
defines the discriminated union that distinguishes betweendog
andcat
based on the discriminatorpet_type
. This reference is then passed onto bothMyFavoritePet
(used in thepet
property) andAllPets
(used in multiple properties). However, once a json-schema is generated using theAllPets.model_json_schema
method, this association is lost since Pydantic generates the discriminators "inline" with the properties. i.e.:This has a couple of problems:
While both are valid under json-spec, if Pydantic were to construct the model using references to
Pet
instead of defining it "inline" every single time both of these would be solved.Luckily, a simple change to the definition of the
Pet
discriminator should fix this issue.When generating the json-schema, we now got the correct references:
For interoperability with other tools, I would greatly appreciate the chance to propose this refactor to the current aind-data-schema. We could even try to come up with a way to add some syntactic sugar so users don't have to worry about these details. Happy to start working on a PR if people think it is worth it!
Beta Was this translation helpful? Give feedback.
All reactions