marvin.utilities.pydantic
Module for Pydantic utilities.
cast_to_model
¶
Casts a type or callable to a Pydantic model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
function_or_type
|
Union[type, type[BaseModel], GenericAlias, Callable[..., Any]]
|
The type or callable to cast to a Pydantic model. |
required |
name
|
Optional[str]
|
The name of the model to create. |
None
|
description
|
Optional[str]
|
The description of the model to create. |
None
|
field_name
|
Optional[str]
|
The name of the field to create. |
None
|
Returns:
Type | Description |
---|---|
type[BaseModel]
|
The Pydantic model created from the given type or callable. |
parse_as
¶
Parse a given data structure as a Pydantic model via TypeAdapter
.
Read more about TypeAdapter
here.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
type_
|
type[T]
|
The type to parse the data as. |
required |
data
|
Any
|
The data to be parsed. |
required |
mode
|
Literal['python', 'json', 'strings']
|
The mode to use for parsing, either |
'python'
|
Returns:
Type | Description |
---|---|
T
|
The parsed |
Example
Basic Usage of parse_as
from marvin.utilities.pydantic import parse_as
from pydantic import BaseModel
class ExampleModel(BaseModel):
name: str
# parsing python objects
parsed = parse_as(ExampleModel, {"name": "Marvin"})
assert isinstance(parsed, ExampleModel)
assert parsed.name == "Marvin"
# parsing json strings
parsed = parse_as(
list[ExampleModel],
'[{"name": "Marvin"}, {"name": "Arthur"}]',
mode="json"
)
assert all(isinstance(item, ExampleModel) for item in parsed)
assert parsed[0].name == "Marvin"
assert parsed[1].name == "Arthur"
# parsing raw strings
parsed = parse_as(int, '123', mode="strings")
assert isinstance(parsed, int)
assert parsed == 123