bagofholding 0.post0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bagofholding/bag.py ADDED
@@ -0,0 +1,266 @@
1
+ """
2
+ The core user-facing object.
3
+
4
+ Full implementations of bags should guarantee the key features promised by the package:
5
+ - Storage and retrieval of arbitrary pickleable python objects
6
+ - Metadata preservation
7
+ - Versioning verification
8
+ - Browsing without loading
9
+ - Partial reloading
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import abc
15
+ import dataclasses
16
+ import os.path
17
+ import pathlib
18
+ import pickle
19
+ from collections.abc import Iterator, Mapping
20
+ from typing import (
21
+ Any,
22
+ ClassVar,
23
+ Self,
24
+ SupportsIndex,
25
+ )
26
+
27
+ import bidict
28
+ from pyiron_snippets import import_alarm
29
+
30
+ from bagofholding.content import BespokeItem, Packer, pack, unpack
31
+ from bagofholding.exceptions import BagMismatchError, InvalidMetadataError
32
+ from bagofholding.metadata import (
33
+ HasFieldIterator,
34
+ HasVersionInfo,
35
+ Metadata,
36
+ VersionScrapingMap,
37
+ VersionValidatorType,
38
+ get_version,
39
+ )
40
+
41
+ try:
42
+ from bagofholding.widget import BagTree
43
+
44
+ alarm = import_alarm.ImportAlarm()
45
+ except (ImportError, ModuleNotFoundError):
46
+ alarm = import_alarm.ImportAlarm(
47
+ "The browsing widget relies on ipytree and traitlets, but this was "
48
+ "unavailable. You can get a text-representation of all available paths with "
49
+ ":meth:`bagofholding.bag.Bag.list_paths`.",
50
+ _fail_on_warning=True,
51
+ )
52
+
53
+ PATH_DELIMITER = "/"
54
+
55
+
56
+ @dataclasses.dataclass(frozen=True)
57
+ class BagInfo(HasVersionInfo, HasFieldIterator):
58
+ pass
59
+
60
+
61
+ class Bag(Packer, Mapping[str, Metadata | None], abc.ABC):
62
+ """
63
+ Bags are the user-facing object.
64
+ """
65
+
66
+ bag_info: BagInfo
67
+ storage_root: ClassVar[str] = "object"
68
+ filepath: pathlib.Path
69
+
70
+ @classmethod
71
+ def get_bag_info(cls) -> BagInfo:
72
+ return BagInfo(
73
+ qualname=cls.__qualname__,
74
+ module=cls.__module__,
75
+ version=cls.get_version(),
76
+ )
77
+
78
+ @classmethod
79
+ def _bag_info_class(cls) -> type[BagInfo]:
80
+ return BagInfo
81
+
82
+ @classmethod
83
+ def save(
84
+ cls,
85
+ obj: Any,
86
+ filepath: str | pathlib.Path,
87
+ require_versions: bool = False,
88
+ forbidden_modules: list[str] | tuple[str, ...] = (),
89
+ version_scraping: VersionScrapingMap | None = None,
90
+ _pickle_protocol: SupportsIndex = pickle.DEFAULT_PROTOCOL,
91
+ overwrite_existing: bool = True,
92
+ ) -> None:
93
+ """
94
+ Save a python object to file.
95
+
96
+ Args:
97
+ obj (Any): The (pickleble) python object to be saved.
98
+ filepath (str|pathlib.Path): The path to save the object to.
99
+ require_versions (bool): Whether to require a metadata for reduced
100
+ and complex objects to contain a non-None version. (Default is False,
101
+ objects can be stored from non-versioned packages/modules.)
102
+ forbidden_modules (list[str] | tuple[str, ...] | None): Do not allow saving
103
+ objects whose root-most modules are listed here. (Default is an empty
104
+ tuple, i.e. don't disallow anything.) This is particularly useful to
105
+ disallow `"__main__"` to improve the odds that objects will actually
106
+ be loadable in the future.
107
+ version_scraping (dict[str, Callable[[str], str]] | None): An optional
108
+ dictionary mapping module names to a callable that takes this name and
109
+ returns a version (or None). The default callable imports the module
110
+ string and looks for a `__version__` attribute.
111
+ """
112
+ if os.path.exists(filepath):
113
+ if overwrite_existing and os.path.isfile(filepath):
114
+ os.remove(filepath)
115
+ else:
116
+ raise FileExistsError(f"{filepath} already exists or is not a file.")
117
+ bag = cls(filepath)
118
+ bag._pack_bag_info()
119
+ pack(
120
+ obj,
121
+ bag,
122
+ bag.storage_root,
123
+ bidict.bidict(),
124
+ [],
125
+ require_versions,
126
+ forbidden_modules,
127
+ version_scraping,
128
+ _pickle_protocol=_pickle_protocol,
129
+ )
130
+ bag._write()
131
+
132
+ @classmethod
133
+ def get_version(cls) -> str:
134
+ return str(get_version(cls.__module__, {}))
135
+
136
+ def __init__(
137
+ self, filepath: str | pathlib.Path, *args: object, **kwargs: Any
138
+ ) -> None:
139
+ super().__init__(*args, **kwargs)
140
+ self.filepath = pathlib.Path(filepath)
141
+ if os.path.isfile(self.filepath):
142
+ self.bag_info = self._unpack_bag_info()
143
+ if not self.validate_bag_info(self.bag_info, self.get_bag_info()):
144
+ raise BagMismatchError(
145
+ f"The bag class {self.__class__} does not match the bag saved at "
146
+ f"{filepath}; class info is {self.get_bag_info()}, but the info saved "
147
+ f"is {self.bag_info}"
148
+ )
149
+
150
+ @abc.abstractmethod
151
+ def _pack_field(self, path: str, key: str, value: str) -> None: ...
152
+
153
+ @abc.abstractmethod
154
+ def _unpack_field(self, path: str, key: str) -> str | None: ...
155
+
156
+ @staticmethod
157
+ def validate_bag_info(bag_info: BagInfo, reference: BagInfo) -> bool:
158
+ return bag_info == reference
159
+
160
+ def load(
161
+ self,
162
+ path: str = storage_root,
163
+ version_validator: VersionValidatorType = "exact",
164
+ version_scraping: VersionScrapingMap | None = None,
165
+ ) -> Any:
166
+ return unpack(
167
+ self,
168
+ path,
169
+ {},
170
+ version_validator=version_validator,
171
+ version_scraping=version_scraping,
172
+ )
173
+
174
+ def __getitem__(self, path: str) -> Metadata:
175
+ return self.unpack_metadata(path)
176
+
177
+ @abc.abstractmethod
178
+ def list_paths(self) -> list[str]:
179
+ """A list of all available content paths."""
180
+
181
+ @alarm
182
+ def widget(self): # type: ignore[no-untyped-def]
183
+ return BagTree(self)
184
+
185
+ def browse(self): # type: ignore[no-untyped-def]
186
+ try:
187
+ return self.widget()
188
+ except ImportError:
189
+ return self.list_paths()
190
+
191
+ def __len__(self) -> int:
192
+ return len(self.list_paths())
193
+
194
+ def __iter__(self) -> Iterator[str]:
195
+ return iter(self.list_paths())
196
+
197
+ def join(self, *paths: str) -> str:
198
+ return PATH_DELIMITER.join(paths)
199
+
200
+ @staticmethod
201
+ def pickle_check(
202
+ obj: Any, raise_exceptions: bool = True, print_message: bool = False
203
+ ) -> str | None:
204
+ """
205
+ A simple helper to check if an object can be pickled and unpickled.
206
+ Useful if you run into trouble saving or loading and want to see whether the
207
+ underlying object is compliant with pickle-ability requirements to begin with.
208
+
209
+ Args:
210
+ obj: The object to test for pickling support.
211
+ raise_exceptions: If True, re-raise any exception encountered.
212
+ print_message: If True, print the exception message on failure.
213
+
214
+ Returns:
215
+ None if pickling is successful; otherwise, returns the exception message as a string.
216
+ """
217
+
218
+ try:
219
+ pickle.loads(pickle.dumps(obj))
220
+ except Exception as e:
221
+ if print_message:
222
+ print(e)
223
+ if raise_exceptions:
224
+ raise e
225
+ return str(e)
226
+ return None
227
+
228
+ def _pack_fields(self, dataclass: HasFieldIterator, path: str) -> None:
229
+ for k, v in dataclass.field_items():
230
+ if v is not None:
231
+ self._pack_field(path, k, v)
232
+
233
+ def _unpack_fields(
234
+ self, dataclass_type: type[HasFieldIterator], path: str
235
+ ) -> dict[str, str | None]:
236
+ field_values: dict[str, str | None] = {}
237
+ for k in dataclass_type.__dataclass_fields__:
238
+ field_values[k] = self._unpack_field(path, k)
239
+ return field_values
240
+
241
+ def _pack_bag_info(self) -> None:
242
+ self._pack_fields(self.get_bag_info(), PATH_DELIMITER)
243
+
244
+ def _unpack_bag_info(self) -> BagInfo:
245
+ return self._bag_info_class()(
246
+ **self._unpack_fields(self._bag_info_class(), PATH_DELIMITER)
247
+ )
248
+
249
+ def _write(self) -> None:
250
+ return
251
+
252
+ def pack_metadata(self, metadata: Metadata, path: str) -> None:
253
+ self._pack_fields(metadata, path)
254
+ return None
255
+
256
+ def unpack_metadata(self, path: str) -> Metadata:
257
+ metadata = self._unpack_fields(Metadata, path)
258
+ content_type = metadata.pop("content_type", None)
259
+ if content_type is None:
260
+ raise InvalidMetadataError(f"Metadata at {path} is missing a content type")
261
+ return Metadata(content_type, **metadata)
262
+
263
+ def get_bespoke_content_class(
264
+ self, obj: object
265
+ ) -> type[BespokeItem[Any, Self]] | None:
266
+ return None