Skip to content

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.

Example

Basic Usage of cast_to_model

from marvin.utilities.pydantic import cast_to_model
from pydantic import BaseModel

def foo(bar: str) -> str:
    return bar

# cast a function to a model
model = cast_to_model(foo, name="Foo")
assert issubclass(model, BaseModel)

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, json, or strings. Defaults to python, where data should be a Python object (e.g. dict).

'python'

Returns:

Type Description
T

The parsed data as the given type_.

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