Validates an object against a given Python type.
| 9 | T = TypeVar("T", covariant=True) |
| 10 | |
| 11 | class TypeChatValidator(Generic[T]): |
| 12 | """ |
| 13 | Validates an object against a given Python type. |
| 14 | """ |
| 15 | |
| 16 | _adapted_type: pydantic.TypeAdapter[T] |
| 17 | |
| 18 | def __init__(self, py_type: type[T]): |
| 19 | """ |
| 20 | Args: |
| 21 | |
| 22 | py_type: The schema type to validate against. |
| 23 | """ |
| 24 | super().__init__() |
| 25 | self._adapted_type = pydantic.TypeAdapter(py_type) |
| 26 | |
| 27 | def validate_object(self, obj: object) -> Result[T]: |
| 28 | """ |
| 29 | Validates the given Python object according to the associated schema type. |
| 30 | |
| 31 | Returns a `Success[T]` object containing the object if validation was successful. |
| 32 | Otherwise, returns a `Failure` object with a `message` property describing the error. |
| 33 | """ |
| 34 | try: |
| 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) |
| 43 | return Success(typed_dict) |
| 44 | except pydantic.ValidationError as validation_error: |
| 45 | return _handle_error(validation_error) |
| 46 | |
| 47 | |
| 48 | def _handle_error(validation_error: pydantic.ValidationError) -> Failure: |
no outgoing calls
no test coverage detected
searching dependent graphs…