-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathschema_util.py
More file actions
30 lines (24 loc) · 917 Bytes
/
schema_util.py
File metadata and controls
30 lines (24 loc) · 917 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
from __future__ import annotations
from typing import Any
try:
import pydantic
pydantic_installed = True
except ImportError:
pydantic_installed = False
def apply_schema(data: Any, schema: Any) -> Any:
"""
Validate and parse data using a Pydantic model class.
Returns the validated data as a plain dict.
Raises ExtrasRequireModuleNotFoundError if pydantic is not installed.
Raises TypeError if schema is not a pydantic BaseModel subclass.
"""
from benedict.extras import require_schema
require_schema(installed=pydantic_installed)
if isinstance(schema, type) and issubclass(schema, pydantic.BaseModel):
schema_cls: type[pydantic.BaseModel] = schema
else:
raise TypeError(
f"schema must be a pydantic BaseModel subclass, got {type(schema)!r}"
)
instance = schema_cls.model_validate(data)
return instance.model_dump()