Skip to content

Base Models

Base model classes for data serialization and deserialization.

Classes

ModelProtocol

A runtime-checkable protocol defining the serialization/deserialization interface (from_dict, to_dict, from_json, to_json, from_path, to_path).

ModelBase

An abstract base class implementing common serialization methods (JSON, YAML, file I/O).

PydanticBaseModel

The primary base class for creating data models, backed by Pydantic with automatic camelCase alias support.

AwareIsoDateTime / IsoDateTime / IsoDate

Annotated Pydantic types for ISO 8601 datetime and date fields with custom parsing and serialization.


ModelBase

Abstract base class implementing common serialization methods.

Provides JSON, YAML, and file I/O serialization. Subclasses must implement from_dict and to_dict.

from_dict abstractmethod classmethod

from_dict(data, **kwargs)

Create an instance from a dictionary.

Parameters:

Name Type Description Default
data JSONObject

Dictionary representation of the model.

required
**kwargs

Additional keyword arguments for deserialization.

{}

Returns:

Type Description
Self

A new instance of the model.

Raises:

Type Description
NotImplementedError

If not implemented by a subclass.

Source code in src/aibs_informatics_core/models/base/_base_model.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@classmethod
@abc.abstractmethod
def from_dict(cls, data: JSONObject, **kwargs) -> Self:
    """Create an instance from a dictionary.

    Args:
        data: Dictionary representation of the model.
        **kwargs: Additional keyword arguments for deserialization.

    Returns:
        A new instance of the model.

    Raises:
        NotImplementedError: If not implemented by a subclass.
    """
    raise NotImplementedError(
        f"Must implement this method in {cls.__name__}"
    )  # pragma: no cover

from_json classmethod

from_json(data, **kwargs)

Create an instance from a JSON string.

Parameters:

Name Type Description Default
data str

JSON string representation of the model.

required
**kwargs

Additional keyword arguments passed to from_dict.

{}

Returns:

Type Description
Self

A new instance of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
156
157
158
159
160
161
162
163
164
165
166
167
@classmethod
def from_json(cls, data: str, **kwargs) -> Self:
    """Create an instance from a JSON string.

    Args:
        data: JSON string representation of the model.
        **kwargs: Additional keyword arguments passed to `from_dict`.

    Returns:
        A new instance of the model.
    """
    return cls.from_dict(json.loads(data), **kwargs)

from_path classmethod

from_path(path, **kwargs)

Create an instance from a JSON or YAML file.

Parameters:

Name Type Description Default
path Path

Path to the file. Files with .yml or .yaml extensions are parsed as YAML; all others are parsed as JSON.

required
**kwargs

Additional keyword arguments passed to from_dict.

{}

Returns:

Type Description
Self

A new instance of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
@classmethod
def from_path(cls, path: Path, **kwargs) -> Self:
    """Create an instance from a JSON or YAML file.

    Args:
        path: Path to the file. Files with `.yml` or `.yaml` extensions
            are parsed as YAML; all others are parsed as JSON.
        **kwargs: Additional keyword arguments passed to `from_dict`.

    Returns:
        A new instance of the model.
    """
    if path.suffix in (".yml", ".yaml"):
        with open(path) as f:
            return cls.from_dict(yaml.safe_load(f), **kwargs)
    else:
        return cls.from_dict(json.loads(path.read_text()), **kwargs)

is_valid classmethod

is_valid(data, **kwargs)

Checks whether model is valid.

Parameters:

Name Type Description Default
data JSONObject

data to validate against model

required
**kwargs

additional kwargs to pass to from_dict method for validation

{}

Returns:

Name Type Description
bool bool

True if the model is valid, False otherwise.

Source code in src/aibs_informatics_core/models/base/_base_model.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
@classmethod
def is_valid(cls, data: JSONObject, **kwargs) -> bool:
    """Checks whether model is valid.

    Args:
        data (JSONObject): data to validate against model
        **kwargs: additional kwargs to pass to from_dict method for validation

    Returns:
        bool: True if the model is valid, False otherwise.
    """
    try:
        cls.from_dict(data, **kwargs)
        return True
    except Exception:
        return False

to_dict abstractmethod

to_dict(**kwargs)

Serialize the model to a dictionary.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments for serialization.

{}

Returns:

Type Description
JSONObject

Dictionary representation of the model.

Raises:

Type Description
NotImplementedError

If not implemented by a subclass.

Source code in src/aibs_informatics_core/models/base/_base_model.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@abc.abstractmethod
def to_dict(self, **kwargs) -> JSONObject:
    """Serialize the model to a dictionary.

    Args:
        **kwargs: Additional keyword arguments for serialization.

    Returns:
        Dictionary representation of the model.

    Raises:
        NotImplementedError: If not implemented by a subclass.
    """
    raise NotImplementedError(
        f"Must implement this method in {self.__class__.__name__}"
    )  # pragma: no cover

to_json

to_json(**kwargs)

Serialize the model to a JSON string.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments passed to to_dict.

{}

Returns:

Type Description
str

JSON string representation of the model (indented with 4 spaces).

Source code in src/aibs_informatics_core/models/base/_base_model.py
169
170
171
172
173
174
175
176
177
178
def to_json(self, **kwargs) -> str:
    """Serialize the model to a JSON string.

    Args:
        **kwargs: Additional keyword arguments passed to `to_dict`.

    Returns:
        JSON string representation of the model (indented with 4 spaces).
    """
    return json.dumps(self.to_dict(**kwargs), indent=4)

to_path

to_path(path, **kwargs)

Serialize the model and write it to a file as JSON.

Parameters:

Name Type Description Default
path Path

Path to the output file.

required
**kwargs

Additional keyword arguments passed to to_json.

{}
Source code in src/aibs_informatics_core/models/base/_base_model.py
198
199
200
201
202
203
204
205
def to_path(self, path: Path, **kwargs):
    """Serialize the model and write it to a file as JSON.

    Args:
        path: Path to the output file.
        **kwargs: Additional keyword arguments passed to `to_json`.
    """
    path.write_text(self.to_json(**kwargs))

ModelProtocol

Bases: Protocol

Runtime-checkable protocol defining the serialization/deserialization interface.

Any class implementing this protocol must provide methods to convert to/from dictionaries, JSON strings, and file paths.

from_dict classmethod

from_dict(data, **kwargs)

Create an instance from a dictionary.

Parameters:

Name Type Description Default
data JSONObject

Dictionary representation of the model.

required
**kwargs

Additional keyword arguments for deserialization.

{}

Returns:

Type Description
Self

A new instance of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
37
38
39
40
41
42
43
44
45
46
47
48
@classmethod
def from_dict(cls: type[Self], data: JSONObject, **kwargs) -> Self:  # pragma: no cover
    """Create an instance from a dictionary.

    Args:
        data: Dictionary representation of the model.
        **kwargs: Additional keyword arguments for deserialization.

    Returns:
        A new instance of the model.
    """
    ...

from_json classmethod

from_json(data, **kwargs)

Create an instance from a JSON string.

Parameters:

Name Type Description Default
data str

JSON string representation of the model.

required
**kwargs

Additional keyword arguments for deserialization.

{}

Returns:

Type Description
Self

A new instance of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
61
62
63
64
65
66
67
68
69
70
71
72
@classmethod
def from_json(cls: type[Self], data: str, **kwargs) -> Self:  # pragma: no cover
    """Create an instance from a JSON string.

    Args:
        data: JSON string representation of the model.
        **kwargs: Additional keyword arguments for deserialization.

    Returns:
        A new instance of the model.
    """
    ...

from_path classmethod

from_path(path, **kwargs)

Create an instance from a file path (JSON or YAML).

Parameters:

Name Type Description Default
path Path

Path to the file to read.

required
**kwargs

Additional keyword arguments for deserialization.

{}

Returns:

Type Description
Self

A new instance of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
85
86
87
88
89
90
91
92
93
94
95
96
@classmethod
def from_path(cls: type[Self], path: Path, **kwargs) -> Self:  # pragma: no cover
    """Create an instance from a file path (JSON or YAML).

    Args:
        path: Path to the file to read.
        **kwargs: Additional keyword arguments for deserialization.

    Returns:
        A new instance of the model.
    """
    ...

to_dict

to_dict(**kwargs)

Serialize the model to a dictionary.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments for serialization.

{}

Returns:

Type Description
JSONObject

Dictionary representation of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
50
51
52
53
54
55
56
57
58
59
def to_dict(self, **kwargs) -> JSONObject:  # pragma: no cover
    """Serialize the model to a dictionary.

    Args:
        **kwargs: Additional keyword arguments for serialization.

    Returns:
        Dictionary representation of the model.
    """
    ...

to_json

to_json(**kwargs)

Serialize the model to a JSON string.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments for serialization.

{}

Returns:

Type Description
str

JSON string representation of the model.

Source code in src/aibs_informatics_core/models/base/_base_model.py
74
75
76
77
78
79
80
81
82
83
def to_json(self, **kwargs) -> str:  # pragma: no cover
    """Serialize the model to a JSON string.

    Args:
        **kwargs: Additional keyword arguments for serialization.

    Returns:
        JSON string representation of the model.
    """
    ...

to_path

to_path(path, **kwargs)

Serialize the model and write it to a file.

Parameters:

Name Type Description Default
path Path

Path to the file to write.

required
**kwargs

Additional keyword arguments for serialization.

{}
Source code in src/aibs_informatics_core/models/base/_base_model.py
 98
 99
100
101
102
103
104
105
def to_path(self, path: Path, **kwargs):  # pragma: no cover
    """Serialize the model and write it to a file.

    Args:
        path: Path to the file to write.
        **kwargs: Additional keyword arguments for serialization.
    """
    ...

PydanticBaseModel

Bases: BaseModel, ModelBase

Base class for Pydantic models that can be serialized to/from JSON

from_dict classmethod

from_dict(data, **kwargs)

Create an instance from a dictionary using Pydantic validation.

Parameters:

Name Type Description Default
data JSONObject

Dictionary representation of the model.

required
**kwargs

Additional keyword arguments passed to model_validate.

{}

Returns:

Type Description
Self

A validated instance of the model.

Raises:

Type Description
ValidationError

If the data fails Pydantic validation.

Source code in src/aibs_informatics_core/models/base/_pydantic_model.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@classmethod
def from_dict(cls, data: JSONObject, **kwargs) -> Self:
    """Create an instance from a dictionary using Pydantic validation.

    Args:
        data: Dictionary representation of the model.
        **kwargs: Additional keyword arguments passed to ``model_validate``.

    Returns:
        A validated instance of the model.

    Raises:
        ValidationError: If the data fails Pydantic validation.
    """
    try:
        return cls.model_validate(data, **filter_kwargs(cls.model_validate, kwargs))
    except PydanticValidationError as e:
        # TODO: Need to figure out whether to use Pydantic's ValidationError or our own,
        #       and how to best preserve error details
        raise ValidationError(str(e)) from e

to_dict

to_dict(**kwargs)

Serialize the model to a dictionary using Pydantic serialization.

By default, None values are excluded and JSON-compatible serialization mode is used.

Parameters:

Name Type Description Default
**kwargs

Additional keyword arguments passed to model_dump. Supports exclude_none (default: True) and mode (default: "json").

{}

Returns:

Type Description
JSONObject

Dictionary representation of the model.

Raises:

Type Description
ValidationError

If serialization fails Pydantic validation.

Source code in src/aibs_informatics_core/models/base/_pydantic_model.py
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
def to_dict(self, **kwargs) -> JSONObject:
    """Serialize the model to a dictionary using Pydantic serialization.

    By default, None values are excluded and JSON-compatible serialization
    mode is used.

    Args:
        **kwargs: Additional keyword arguments passed to ``model_dump``.
            Supports ``exclude_none`` (default: True) and ``mode``
            (default: "json").

    Returns:
        Dictionary representation of the model.

    Raises:
        ValidationError: If serialization fails Pydantic validation.
    """
    # Ensure None values are excluded by default to mirror DataClassJsonMixin settings
    exclude_none = kwargs.pop("exclude_none", True)
    mode = kwargs.pop("mode", "json")
    try:
        return self.model_dump(
            mode=mode,  # Use JSON serialization mode
            exclude_none=exclude_none,  # Exclude None values by default
            **filter_kwargs(self.model_dump, kwargs),
        )
    except PydanticValidationError as e:
        raise ValidationError(str(e)) from e