-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathpydantic_util.py
More file actions
36 lines (25 loc) · 902 Bytes
/
pydantic_util.py
File metadata and controls
36 lines (25 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from typing import Any
from benedict.extras import require_validate
try:
from pydantic import BaseModel
pydantic_installed = True
except ModuleNotFoundError:
pydantic_installed = False
BaseModel = None
PydanticModel = type["BaseModel"]
def _is_pydantic_model(obj: Any) -> bool:
"""
Check if an object is a Pydantic model class.
"""
return pydantic_installed and isinstance(obj, type) and issubclass(obj, BaseModel)
def validate_data(data: Any, *, schema: PydanticModel | None = None) -> Any:
"""
Validate data against a Pydantic schema if provided.
"""
if schema is None:
return data
require_validate(installed=pydantic_installed)
if not _is_pydantic_model(schema):
raise ValueError("Invalid schema. Schema must be a Pydantic model class.")
validated = schema.model_validate(data)
return validated.model_dump()