New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proper support for functional discriminators #7462
Comments
Ah sorry if I was a bit unclear in #7391 In this particular case I can see how your suggestion would work for serialization -- however not sure it's gonna work for deserializing ( |
Side note -- looks like David has already made significant progress in this department: #6915. Will touch base with the team on this tmrw morning. |
Would this (or something else) support dynamically registering members that are not know when defining the Specifically, I'm unsure whether Happy to open/move to a separate issue if this isn't the right place. (edit: #7366 might be the better issue, but is closed and points here.) For example, I've worked on 3 unrelated projects where a base class defines a couple fields but is then "dynamically" subclassed with more fields. In two of the projects, external users are creating the subclasses outside the library, hence can't be know ahead of time (but we can implement a plugin/registration mechanism to ensure they are know by the time we try (de)serialization). The other project uses separate modules to avoid circular imports, so maintaining the The reason we'd like a discriminated union here, instead of just hinting with the base class, is because of these additional fields defined on the subclasses. If a wrapping model is just hinted with the base class, the extra fields are discarded. Perhaps just updating class Base(BaseModel):
kind: str
base_discriminator = Discriminator(...)
class Container(BaseModel):
data: Annotated[Base, base_discriminator]
... # elsewhere
class A(Base):
kind: Literal["A"] = "A"
a: int
base_discriminator.choices["A"] = A
class B(Base):
kind: Literal["B"] = "B"
b: int
base_discriminator.choices["B"] = B (in reality, probably made easier with |
Ta da! Closed by #7983 🥳 |
Initial Checks
Description
this is supported in pydantic-core, see here but doesn't seem to be well supported in Pydantic V2.
I propose we add a new type:
Obviously
Discriminator
should behave the same asField(discriminator='...')
when it's used with a string.Which could be used like this:
Related to #7391 but deserved a better explanation.
Affected Components
.model_dump()
and.model_dump_json()
model_construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: