Coverage for src/cvx/bson/dataclass.py: 94%
16 statements
« prev ^ index » next coverage.py v7.10.3, created at 2025-08-17 08:01 +0000
« prev ^ index » next coverage.py v7.10.3, created at 2025-08-17 08:01 +0000
1# Copyright 2023 Stanford University Convex Optimization Group
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Dataclass utilities for BSON serialization and deserialization."""
16from dataclasses import dataclass
17from typing import Any
19from .file import FILE, read_bson, write_bson
22@dataclass(frozen=True)
23class Data:
24 """Base class for dataclasses that can be serialized to and from BSON.
26 This class provides methods for serializing to BSON files and deserializing from BSON files.
27 """
29 def to_bson(self, file: FILE) -> int:
30 """Serialize this object to a BSON file.
32 Args:
33 file: Path to the file where the data will be written
35 Returns:
36 Number of bytes written
37 """
38 return write_bson(file, self.__dict__)
40 @classmethod
41 def from_bson(cls, file: FILE) -> Any:
42 """Create an instance of this class from a BSON file.
44 Args:
45 file: Path to the BSON file to read
47 Returns:
48 An instance of this class
49 """
50 x = read_bson(file)
51 return cls(**x)
53 @classmethod
54 def keys(cls):
55 """Get the field names of this dataclass.
57 Yields:
58 Field names defined in the class annotations
59 """
60 yield from cls.__dict__["__annotations__"].keys()
62 def items(self):
63 """Get the field names and values of this dataclass instance.
65 Yields:
66 Pairs of (field_name, field_value)
67 """
68 yield from self.__dict__.items()