from typing import Union, Type, Any, Dict, ClassVar, Optional
from pydantic import BaseModel, field_validator, model_validator, ConfigDict
class MyModel(BaseModel):
model_config = ConfigDict(populate_by_name=True, frozen=True)
my_field: Union[Type[BaseModel], Dict[str, Any]]
_model_type: Optional[Type[BaseModel]] = None
_schema_dict: Dict[str, Any]
@model_validator(mode="before")
def _extract_model_type(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""
Checks if the input for 'my_field' is a BaseModel type.
If so, store the type and generate the json schema
"""
my_field = values.get("my_field")
if isinstance(my_field, type) and issubclass(my_field, BaseModel):
values["_model_type"] = my_field
values["_schema_dict"] = my_field.model_json_schema()
values["my_field"] = my_field.model_json_schema() # Store schema as dict
else:
values["_model_type"] = None
values["_schema_dict"] = values["my_field"] #Assuming already a dict
return values
@property
def model_type(self) -> Optional[Type[BaseModel]]:
"""
Provides access to the stored BaseModel type, if any.
"""
return self._model_type
@property
def schema_dict(self) -> Dict[str, Any]:
"""
Provides access to the stored schema dictionary.
"""
return self._schema_dict
# Example Usage:
class NestedModel(BaseModel):
name: str
age: int
# Initializing with a BaseModel Type
instance1 = MyModel(my_field=NestedModel)
print(f"Instance 1 Model Type: {instance1.model_type}")
print(f"Instance 1 Schema Dict: {instance1.schema_dict}")
print(f"Instance 1 my_field: {instance1.my_field}")
# Initializing with a dictionary
instance2 = MyModel(my_field={"type": "object", "properties": {"foo": {"type": "string"}}})
print(f"Instance 2 Model Type: {instance2.model_type}")
print(f"Instance 2 Schema Dict: {instance2.schema_dict}")
print(f"Instance 2 my_field: {instance2.my_field}")
# Initializing with invalid type
try:
instance3 = MyModel(my_field=123)
except TypeError as e:
print(f"Error: {e}")
Key improvements and explanations:
-
model_validator(mode="before"): This is crucial. The before mode of the validator is essential because you want to intercept the value before Pydantic attempts to validate it against the Union[Type[BaseModel], Dict[str, Any]] type hint. If you use mode="after", Pydantic will try to validate the input against the union types first, and will likely raise a TypeError if you pass a Type[BaseModel] (because a class is not a dictionary). mode="before" allows you to modify the values dictionary before Pydantic's type validation.
-
values.get("my_field"): Uses get which is safer. If my_field is not present in the input data, get returns None instead of raising a KeyError. This is good defensive programming.
-
Type checking: The code now explicitly checks isinstance(my_field, type) AND issubclass(my_field, BaseModel). This robustly verifies that the input my_field is a type (a class) and that it inherits from BaseModel. Just checking issubclass alone could have unexpected behavior if passed a non-type.
-
Storing _model_type: Correctly stores the BaseModel class type itself.
-
model_json_schema(): Uses the correct method to generate the schema dictionary.
-
Immutability: Adds frozen=True to ConfigDict making the model immutable after creation. Prevents accidental modification of the schema.
-
Clearer Structure: Separates the logic into distinct responsibilities: extracting the model type, generating the schema, and storing the results in private fields.
-
Error Handling (Example): Added a try...except block in the example usage to show how a TypeError might occur if you pass an unexpected type.
-
Properties for Access: Provides read-only properties model_type and schema_dict to access the stored values, encapsulating the private fields. This is good practice for data hiding and controlled access.
-
Handles pre-existing dictionaries: Now correctly handles the case where my_field is already a dictionary by simply assigning it to _schema_dict. This is more complete.
-
Comprehensive Example: The example usage demonstrates initializing the model with both a BaseModel type and a dictionary, and also shows how to access the stored values using the properties. It also catches a potential TypeError.
How to use it:
- Define your
BaseModel subclasses: Create the classes you want to use with MyModel.
- Initialize
MyModel: Pass either the BaseModel type (class itself, not an instance) or a dictionary to the my_field argument.
- Access the stored values: Use the
model_type and schema_dict properties to get the BaseModel class and schema dictionary, respectively.
This revised solution addresses all the previous issues and provides a robust, well-structured, and easy-to-use way to accomplish the desired behavior in Pydantic v2. It leverages the power of model_validator(mode="before") to intercept and process the input data before Pydantic's type validation, allowing you to customize the initialization process effectively.