22from typing_extensions import Generic , TypeVar
33
44import pydantic
5+ import pydantic_core
56
67from typechat ._internal .result import Failure , Result , Success
78
@@ -26,14 +27,19 @@ def __init__(self, py_type: type[T]):
2627 def validate_object (self , obj : object ) -> Result [T ]:
2728 """
2829 Validates the given Python object according to the associated schema type.
29-
30- Useful for translators that may presume a non-JSON output.
3130
3231 Returns a `Success[T]` object containing the object if validation was successful.
3332 Otherwise, returns a `Failure` object with a `message` property describing the error.
3433 """
3534 try :
36- typed_dict = self ._adapted_type .validate_python (obj , strict = True )
35+ # TODO: Switch to `validate_python` when validation modes are exposed.
36+ # https://github.com/pydantic/pydantic-core/issues/712
37+ # We'd prefer to keep `validate_object` as the core method and
38+ # allow translators to concern themselves with the JSON instead.
39+ # However, under Pydantic's `strict` mode, a `dict` isn't considered compatible
40+ # with a dataclass. So for now, jump back to JSON and validate the string.
41+ json_str = pydantic_core .to_json (obj )
42+ typed_dict = self ._adapted_type .validate_json (json_str , strict = True )
3743 return Success (typed_dict )
3844 except pydantic .ValidationError as validation_error :
3945 return _handle_error (validation_error )
0 commit comments