Replies: 3 comments
|
I can reproduce this on Pydantic 2.13.5. The Pydantic treats metadata exposing Use a plain immutable metadata object instead: from dataclasses import dataclass
from typing import Annotated
from pydantic import BaseModel
@dataclass(frozen=True)
class MetaData:
metadata: str
class Child(BaseModel):
param: Annotated[str, MetaData("metadata")]
class Parent(BaseModel):
child: Child
assert Parent.model_validate(
{"child": {"param": "test"}}
) == Parent(child=Child(param="test"))
assert Child.model_fields["param"].metadata == [MetaData("metadata")]I verified both assertions on 2.13.5. If the metadata is meant to alter validation, implement the schema hook deliberately; if it is only information you inspect later, a frozen dataclass is the safer representation. This looks like an unintended hook collision rather than |
|
See also #12096. You are unfortunately hitting edge cases of the confusing |
|
This happens because in Pydantic v2, every When Pydantic generates schemas for nested models, its schema generator inspects all metadata objects inside Workarounds / Solutions:1. Use a standard Python
|
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I ran into an issue when trying to annotate fields with instances of other pydantic models. My use case is that I have defined a model which contains some metadata (
MetaDataModel) that I'd like to attach to certain fields on other pydantic models, to then use later during validation. The problem is that if I have a "child" modelChildwith a fieldparamthat is, e.g., astrannotated with an instance ofMetaDataModel, and then another "parent" modelParentwith a fieldchildof typeChild, then I get a validation error when trying to validate aParentinstance, with the error saying that the fieldchild.paramshould be typeMetaDataModel, instead of typestr(see example script below).I am wondering- is this intended behavior, or is something wrong here? I can't find much explanation of how the Annotated pattern is parsed in the docs, but maybe I'm missing something. If this is intended behavior, is there a workaround?
I'm using python version 3.13.12 and pydantic version 2.13.5.
Thanks!
All reactions