aidevelopementtoolkit.data_utils.pydantic_utils

models_to_numpy(models: Iterable[BaseModel], fields: Sequence[str]) -> np.ndarray

Extract numeric fields from a sequence of Pydantic models into a NumPy array.

Parameters:
  • models (Iterable[BaseModel]) –

    An iterable of Pydantic model instances to extract values from.

  • fields (Sequence[str]) –

    Ordered sequence of dot-separated field paths (case-sensitive) to extract from each model. Each path is resolved via get_field_value.

Returns:
  • ndarray

    Array containing the extracted values. Shape (N, F): - N: The number of models in the input iterable. - F: The number of requested fields.

Examples:

>>> class Point(BaseModel):
...     x: float
...     y: float
>>> points = [Point(x=1.0, y=2.0), Point(x=3.0, y=4.0)]
>>> models_to_numpy(points, ["x", "y"])
array([[1., 2.],
       [3., 4.]], dtype=float32)
Source code in aidevelopementtoolkit/data_utils/pydantic_utils.py
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
37
38
39
40
41
42
43
44
45
46
47
48
def models_to_numpy(models: Iterable[BaseModel], fields: Sequence[str]) -> np.ndarray:
    """Extract numeric fields from a sequence of Pydantic models into a NumPy array.

    Parameters
    ----------
    models : Iterable[BaseModel]
        An iterable of Pydantic model instances to extract values from.

    fields : Sequence[str]
        Ordered sequence of dot-separated field paths (case-sensitive) to
        extract from each model. Each path is resolved via `get_field_value`.

    Returns
    -------
    np.ndarray
        Array containing the extracted values. Shape `(N, F)`:
        - `N`: The number of models in the input iterable.
        - `F`: The number of requested fields.

    Examples
    --------
    >>> class Point(BaseModel):
    ...     x: float
    ...     y: float
    >>> points = [Point(x=1.0, y=2.0), Point(x=3.0, y=4.0)]
    >>> models_to_numpy(points, ["x", "y"])
    array([[1., 2.],
           [3., 4.]], dtype=float32)
    """

    if not fields:
        logger.error("Expected at least one field name.")
        raise ValueError()

    rows = [
        [get_field_value(model, field) for field in fields]
        for model in models
    ]
    return np.array(rows, dtype=np.float32)

get_field_value(model: BaseModel, field_path: str) -> Any

Retrieve a nested field value from a Pydantic model by dot-separated path.

Parameters:
  • model (BaseModel) –

    The Pydantic model instance to traverse.

  • field_path (str) –

    Dot-separated path to the target field (case-sensitive). For example, "address.city" retrieves model.address.city.

Returns:
  • Any

    The value at the specified field path.

Examples:

>>> class Address(BaseModel):
...     city: str
>>> class User(BaseModel):
...     name: str
...     address: Address
>>> user = User(name="Alice", address=Address(city="Rome"))
>>> get_field_value(user, "name")
'Alice'
>>> get_field_value(user, "address.city")
'Rome'
Source code in aidevelopementtoolkit/data_utils/pydantic_utils.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def get_field_value(
        model: BaseModel,
        field_path: str,
    ) -> Any:
    """Retrieve a nested field value from a Pydantic model by dot-separated path.

    Parameters
    ----------
    model : BaseModel
        The Pydantic model instance to traverse.

    field_path : str
        Dot-separated path to the target field (case-sensitive).
        For example, `"address.city"` retrieves `model.address.city`.

    Returns
    -------
    Any
        The value at the specified field path.

    Examples
    --------
    >>> class Address(BaseModel):
    ...     city: str
    >>> class User(BaseModel):
    ...     name: str
    ...     address: Address
    >>> user = User(name="Alice", address=Address(city="Rome"))
    >>> get_field_value(user, "name")
    'Alice'
    >>> get_field_value(user, "address.city")
    'Rome'
    """
    head, _, tail = field_path.partition(".")
    if isinstance(model, (list, tuple)):
        value = model[int(head)]
    else:
        value = getattr(model, head)
    if tail:
        return get_field_value(value, tail)
    return value

set_field_value(model: BaseModel, field_path: str, value: Any) -> None

Set a nested field value on a Pydantic model by dot-separated path.

Parameters:
  • model (BaseModel) –

    The Pydantic model instance to modify.

  • field_path (str) –

    Dot-separated path to the target field (case-sensitive). For example, "address.city" sets model.address.city.

  • value (Any) –

    The value to assign to the target field.

Raises:
  • AttributeError

    If any segment of the path does not exist on the current model.

Examples:

>>> class Address(BaseModel):
...     city: str
>>> class User(BaseModel):
...     model_config = ConfigDict(frozen=False)
...     name: str
...     address: Address
>>> user = User(name="Alice", address=Address(city="Rome"))
>>> set_field_value(user, "name", "Bob")
>>> user.name
'Bob'
>>> set_field_value(user, "address.city", "Milan")
>>> user.address.city
'Milan'
Source code in aidevelopementtoolkit/data_utils/pydantic_utils.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def set_field_value(
        model: BaseModel,
        field_path: str,
        value: Any,
    ) -> None:
    """Set a nested field value on a Pydantic model by dot-separated path.

    Parameters
    ----------
    model : BaseModel
        The Pydantic model instance to modify.

    field_path : str
        Dot-separated path to the target field (case-sensitive).
        For example, `"address.city"` sets `model.address.city`.

    value : Any
        The value to assign to the target field.

    Raises
    ------
    AttributeError
        If any segment of the path does not exist on the current model.

    Examples
    --------
    >>> class Address(BaseModel):
    ...     city: str
    >>> class User(BaseModel):
    ...     model_config = ConfigDict(frozen=False)
    ...     name: str
    ...     address: Address
    >>> user = User(name="Alice", address=Address(city="Rome"))
    >>> set_field_value(user, "name", "Bob")
    >>> user.name
    'Bob'
    >>> set_field_value(user, "address.city", "Milan")
    >>> user.address.city
    'Milan'
    """
    head, _, tail = field_path.partition(".")
    if tail:
        if isinstance(model, (list, tuple)):
            set_field_value(model[int(head)], tail, value)
        else:
            set_field_value(getattr(model, head), tail, value)
    else:
        if isinstance(model, (list, tuple)):
            model[int(head)] = value
        else:
            setattr(model, head, value)