In pydantic v2, I have a field, that is a union between a type[BaseModel] and a…
- User
In pydantic v2, I have a field, that is a union between a type[BaseModel] and a dict[str, Any]
What I want to accomplish, is that when initializing the model, to check if the the type was type[BaseModel]
If so, I want to store this reference in a private field, while at the same time calling model_json_schema and storing that value as a dict[str, Any]
How do I accomplish this
- Assistant
You can accomplish this using Pydantic v2's
model_validatoror a custom field validator. Here's a solution usingmodel_validator:from pydantic import BaseModel, model_validator from typing import Any, Union, Type class MyModel(BaseModel): schema_field: Union[Type[BaseModel], dict[str, Any]] _original_model: Type[BaseModel] | None = None # Private field to store the model reference @model_validator(mode='before') @classmethod def convert_model_to_schema(cls, data: Any) -> Any: if isinstance(data, dict) and 'schema_field' in data: schema_value = data['schema_field'] # Check if it's a BaseModel subclass if isinstance(schema_value, type) and issubclass(schema_value, BaseModel): # Store the original model class data['_original_model'] = schema_value # Convert to JSON schema data['schema_field'] = schema_value.model_json_schema() return data class Config: # Allow the private field to be set extra = 'allow'Here's an alternative approach using a field validator with
@field_validator:from pydantic import BaseModel, field_validator, PrivateAttr from typing import Any, Union, Type class MyModel(BaseModel): schema_field: Union[Type[BaseModel], dict[str, Any]] _original_model: Type[BaseModel] | None = PrivateAttr(default=None) @field_validator('schema_field', mode='before') @classmethod def convert_model_to_schema(cls, v: Any, info) -> dict[str, Any]: if isinstance(v, type) and issubclass(v, BaseModel): # Store the original model in the instance being created # This is a bit tricky with field validators, so we'll use model_validator instead return v.model_json_schema() return v def model_post_init(self, __context: Any) -> None: # This won't work as expected because the original value is already transformed passThe cleanest approach is actually to use a custom property with a private attribute:
from pydantic import BaseModel, PrivateAttr, field_validator from typing import Any, Union, Type class MyModel(BaseModel): schema_field: dict[str, Any] _original_model: Type[BaseModel] | None = PrivateAttr(default=None) @field_validator('schema_field', mode='before') @classmethod def convert_model_to_schema(cls, v: Any) -> dict[str, Any]: if isinstance(v, type) and issubclass(v, BaseModel): # We need to store this somehow for later use cls._temp_model = v # Temporary storage return v.model_json_schema() return v def model_post_init(self, __context: Any) -> None: # Retrieve the temporary model if it exists if hasattr(self.__class__, '_temp_model'): self._original_model = self.__class__._temp_model delattr(self.__class__, '_temp_model')However, the most robust solution is to use a root validator that handles both fields:
from pydantic import BaseModel, model_validator, PrivateAttr from typing import Any, Union, Type class MyModel(BaseModel): schema_field: dict[str, Any] _original_model: Type[BaseModel] | None = PrivateAttr(default=None) @model_validator(mode='before') @classmethod def process_schema_field(cls, data: Any) -> Any: if isinstance(data, dict) and 'schema_field' in data: schema_value = data['schema_field'] if isinstance(schema_value, type) and issubclass(schema_value, BaseModel): # Create a new dict with the processed values return { **data, 'schema_field': schema_value.model_json_schema(), '_original_model': schema_value } return data # Usage example class SampleModel(BaseModel): name: str age: int # Initialize with a model class instance = MyModel(schema_field=SampleModel) print(instance.schema_field) # Will print the JSON schema print(instance._original_model) # Will print <class 'SampleModel'> # Initialize with a dict instance2 = MyModel(schema_field={"type": "object", "properties": {}}) print(instance2.schema_field) # Will print the dict as-is print(instance2._original_model) # Will print NoneThe first solution with
model_validatoris the cleanest and most straightforward approach. It intercepts the data before field validation, checks ifschema_fieldis a BaseModel subclass, and if so, stores the reference in_original_modelwhile converting the field value to its JSON schema representation.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.