Independently rebuild nested models when used within other core schema generation contexts
https://github.com/pydantic/pydantic/pull/11388 refactored how fields (in particular incomplete fields) were handled during core schema generation. It fixed a class of issues where FieldInfo instances of a model referenced by another model were wrongly mutated:
class Sub(BaseModel):
f: 'Forward'
# Sub.f is incomplete
class Main(BaseModel):
sub: Sub
# When building `Main`, building field `sub` would mutate the `FieldInfo` instance
# of `Sub.f`, leading to all kind of issues.
# Sub.f is completeThis is no longer the case today. When encountering an incomplete sub model (e.g. Sub in our example), we independently re-collect model fields without altering anything on Sub:
And https://github.com/pydantic/pydantic/pull/11388 states:
On important thing to acknowledge: when encountering
sub: Sub, we don't callSub.model_rebuild(). Doing so might be the right thing to do, but is unfortunately not backwards compatible. The reason is that the NS Resolver used forModelmight contain annotations (e.g. provided through theparent_namespace) that should be available forSub. This means that even ifsub: Subsuccessfully builds,Subisn't complete yet — each model should be rebuilt independently, throughmodel_rebuild()).
This backwards compatibility edge case is covered in this test:
However, this is a missed opportunity, in particular when using defer_build. Most of the time, it is perfectly fine to have Sub being rebuilt, without risks of polluting namespace resolution:
class Sub(BaseModel, defer_build=True):
f: int
class Main1(BaseModel):
sub: Sub
# At this point, Sub is still incomplete
class Main2(BaseModel):
sub: Sub
# At this point, Sub is still incomplete too,
# and the building process of Sub was done twiceIn particular, this means prebuilt validator/serializer reuse (introduced in https://github.com/pydantic/pydantic-core/pull/1616) wont work here. Measured on https://github.com/Kludex/httpx2-k8s, this goes from ~24MB to 5MB.
Source: pydantic/pydantic