bagofholding 0.post0.dev1__tar.gz
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-0.post0.dev1/LICENSE +28 -0
- bagofholding-0.post0.dev1/MANIFEST.in +1 -0
- bagofholding-0.post0.dev1/PKG-INFO +204 -0
- bagofholding-0.post0.dev1/bagofholding/__init__.py +20 -0
- bagofholding-0.post0.dev1/bagofholding/_version.py +21 -0
- bagofholding-0.post0.dev1/bagofholding/bag.py +266 -0
- bagofholding-0.post0.dev1/bagofholding/content.py +897 -0
- bagofholding-0.post0.dev1/bagofholding/exceptions.py +44 -0
- bagofholding-0.post0.dev1/bagofholding/h5/__init__.py +0 -0
- bagofholding-0.post0.dev1/bagofholding/h5/bag.py +183 -0
- bagofholding-0.post0.dev1/bagofholding/h5/content.py +29 -0
- bagofholding-0.post0.dev1/bagofholding/h5/context.py +58 -0
- bagofholding-0.post0.dev1/bagofholding/h5/dtypes.py +73 -0
- bagofholding-0.post0.dev1/bagofholding/h5/triebag.py +322 -0
- bagofholding-0.post0.dev1/bagofholding/metadata.py +197 -0
- bagofholding-0.post0.dev1/bagofholding/retrieve.py +52 -0
- bagofholding-0.post0.dev1/bagofholding/trie.py +178 -0
- bagofholding-0.post0.dev1/bagofholding/widget.py +109 -0
- bagofholding-0.post0.dev1/bagofholding.egg-info/PKG-INFO +204 -0
- bagofholding-0.post0.dev1/bagofholding.egg-info/SOURCES.txt +25 -0
- bagofholding-0.post0.dev1/bagofholding.egg-info/dependency_links.txt +1 -0
- bagofholding-0.post0.dev1/bagofholding.egg-info/requires.txt +10 -0
- bagofholding-0.post0.dev1/bagofholding.egg-info/top_level.txt +1 -0
- bagofholding-0.post0.dev1/docs/README.md +145 -0
- bagofholding-0.post0.dev1/pyproject.toml +89 -0
- bagofholding-0.post0.dev1/setup.cfg +4 -0
- bagofholding-0.post0.dev1/setup.py +8 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025, Karlsruhe Institute of Technology - Institute of Nanotechnology
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
* Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
* Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
include LICENSE
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bagofholding
|
|
3
|
+
Version: 0.post0.dev1
|
|
4
|
+
Summary: bagofholding - browsable, partially-reloadable serialization for pickleable python objects.
|
|
5
|
+
Author-email: Liam Huber <liamhuber@greyhavensolutions.com>
|
|
6
|
+
License: BSD 3-Clause License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025, Karlsruhe Institute of Technology - Institute of Nanotechnology
|
|
9
|
+
|
|
10
|
+
Redistribution and use in source and binary forms, with or without
|
|
11
|
+
modification, are permitted provided that the following conditions are met:
|
|
12
|
+
|
|
13
|
+
* Redistributions of source code must retain the above copyright notice, this
|
|
14
|
+
list of conditions and the following disclaimer.
|
|
15
|
+
|
|
16
|
+
* Redistributions in binary form must reproduce the above copyright notice,
|
|
17
|
+
this list of conditions and the following disclaimer in the documentation
|
|
18
|
+
and/or other materials provided with the distribution.
|
|
19
|
+
|
|
20
|
+
* Neither the name of the copyright holder nor the names of its
|
|
21
|
+
contributors may be used to endorse or promote products derived from
|
|
22
|
+
this software without specific prior written permission.
|
|
23
|
+
|
|
24
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
25
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
26
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
27
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
28
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
29
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
30
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
31
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
32
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
33
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
34
|
+
|
|
35
|
+
Project-URL: Homepage, https://pyiron.org/
|
|
36
|
+
Project-URL: Documentation, https://bagofholding.readthedocs.io
|
|
37
|
+
Project-URL: Repository, https://github.com/pyiron/bagofholding
|
|
38
|
+
Keywords: pyiron
|
|
39
|
+
Classifier: Development Status :: 3 - Alpha
|
|
40
|
+
Classifier: Topic :: Scientific/Engineering
|
|
41
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
42
|
+
Classifier: Intended Audience :: Science/Research
|
|
43
|
+
Classifier: Operating System :: OS Independent
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
45
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
46
|
+
Requires-Python: <3.14,>=3.12
|
|
47
|
+
Description-Content-Type: text/markdown
|
|
48
|
+
License-File: LICENSE
|
|
49
|
+
Requires-Dist: bidict==0.23.1
|
|
50
|
+
Requires-Dist: h5py<3.15.0,>=3.14.0
|
|
51
|
+
Requires-Dist: mpi4py<4.1.0,>=4.0.1
|
|
52
|
+
Requires-Dist: numpy<2.4.0,>=2.3.0
|
|
53
|
+
Requires-Dist: pygtrie<2.6.0,>=2.5.0
|
|
54
|
+
Requires-Dist: pyiron_snippets==0.2.0
|
|
55
|
+
Provides-Extra: widget
|
|
56
|
+
Requires-Dist: ipytree==0.2.2; extra == "widget"
|
|
57
|
+
Requires-Dist: traitlets==5.14.3; extra == "widget"
|
|
58
|
+
Dynamic: license-file
|
|
59
|
+
|
|
60
|
+
# bagofholding
|
|
61
|
+
|
|
62
|
+
`bagofholding` is designed to be an easy stand-in for `pickle` serialization for python object that is transparent, flexible, and suitable for long-term storage.
|
|
63
|
+
|
|
64
|
+
## Advantages
|
|
65
|
+
### Drop-in replacement
|
|
66
|
+
|
|
67
|
+
`bagofholding` stores (almost) any `pickle`-able python object, and can be easily used as a drop-in replacement for `pickle` serialization:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
>>> import bagofholding as boh
|
|
71
|
+
>>>
|
|
72
|
+
>>> boh.H5Bag.save(42, "file.h5")
|
|
73
|
+
>>> print(boh.H5Bag("file.h5").load())
|
|
74
|
+
42
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
### Browseable
|
|
80
|
+
|
|
81
|
+
The contents of stored objects can be browsed without actually re-instantiating any of the stored data.
|
|
82
|
+
In the example above, we saw that saving is a class-method, while loading is an instance method.
|
|
83
|
+
We can grab the "bag" instance and use it to peek at what's inside!
|
|
84
|
+
|
|
85
|
+
Let's use a slightly more complex object.
|
|
86
|
+
Readers familiar with `pickle` will be able to see that the "reduced" structure of the object is captured in the structure of the storage itself:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
>>> class MyThing:
|
|
90
|
+
... def __init__(self, answer: int, question: str):
|
|
91
|
+
... self.answer = answer
|
|
92
|
+
... self.question = question
|
|
93
|
+
>>>
|
|
94
|
+
>>> something = MyThing(42, "still computing...")
|
|
95
|
+
>>> boh.H5Bag.save(something, "something.h5")
|
|
96
|
+
>>> bag = boh.H5Bag("something.h5")
|
|
97
|
+
>>> bag.list_paths()
|
|
98
|
+
['object', 'object/args', 'object/args/i0', 'object/constructor', 'object/item_iterator', 'object/kv_iterator', 'object/state', 'object/state/answer', 'object/state/question']
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Item-access on the bag object gives access to metadata stored alongside the actual serialized information:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
>>> bag["object"]
|
|
106
|
+
Metadata(content_type='bagofholding.content.Reducible', qualname='MyThing', module='__main__', version=None, meta=None)
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
For Jupyter users, we power-up browsing capabilities with a widget under `bag.browse()` which lets you navigate the tree and see both metadata values and stored types:
|
|
111
|
+
|
|
112
|
+

|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
### Partial-loading
|
|
116
|
+
|
|
117
|
+
Stored objects can also be re-instantiated _in part_ by leveraging their storage path:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
>>> bag.load("object/state/answer")
|
|
121
|
+
42
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Note that we didn't re-instantiate any part of the object other than this one integer!
|
|
126
|
+
|
|
127
|
+
This feature is incredibly useful for long-term storage and data transferability, as the loading environment does not need to fully match the saving environment -- only the environment required to load the actual piece of data desired matches.
|
|
128
|
+
Consider some complex object which, ultimately, contains important or expensive-to-calculate numeric data, e.g. in the form of numpy array.
|
|
129
|
+
With `bagofholding`, you can pass this data to a colleague running a different python environment, or come back to it years later.
|
|
130
|
+
With only `bagofholding` and `numpy` installed, the end user can browse through the stored object, access, and load only the valuable numeric data without re-installing the entire original environment.
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
### Version control
|
|
134
|
+
|
|
135
|
+
In the examples above, we saw that version (and of course package) information is part of the stored metadata.
|
|
136
|
+
This is useful post-facto for knowing what packages need to be installed to properly load your serialized data.
|
|
137
|
+
You can also specify at load-time how strict or relaxed `bagofholding` should be in re-instantiating data if a stored version does not match the currently installed version, thus protecting you from flawed re-instantiations.
|
|
138
|
+
|
|
139
|
+
`bagofholding` also provides tools to act on this data a-priori.
|
|
140
|
+
To increase the likelihood that stored data will be accessible in the future, you can outlaw any (sub)objects coming from particular modules:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
import bagofholding.exception
|
|
144
|
+
>> > try:
|
|
145
|
+
...
|
|
146
|
+
boh.H5Bag.save(something, "will_fail.h5", forbidden_modules=("__main__",))
|
|
147
|
+
... except bagofholding.exception.ModuleForbiddenError as e:
|
|
148
|
+
...
|
|
149
|
+
print(e)
|
|
150
|
+
Module
|
|
151
|
+
'__main__' is forbidden as a
|
|
152
|
+
source
|
|
153
|
+
of
|
|
154
|
+
stored
|
|
155
|
+
objects.Change
|
|
156
|
+
the
|
|
157
|
+
`forbidden_modules` or move
|
|
158
|
+
this
|
|
159
|
+
object
|
|
160
|
+
to
|
|
161
|
+
an
|
|
162
|
+
allowed
|
|
163
|
+
module.
|
|
164
|
+
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
And/or demand that all objects have an identifiable version that:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
import bagofholding.exception
|
|
171
|
+
>> > try:
|
|
172
|
+
...
|
|
173
|
+
boh.H5Bag.save(something, "will_fail.h5", require_versions=True)
|
|
174
|
+
... except bagofholding.exception.NoVersionError as e:
|
|
175
|
+
...
|
|
176
|
+
print(e)
|
|
177
|
+
Could
|
|
178
|
+
not find
|
|
179
|
+
a
|
|
180
|
+
version
|
|
181
|
+
for __main__.Either disable `require_versions`, use `version_scraping` to find an existing version for this package, or add versioning to the unversioned package.
|
|
182
|
+
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Of course, metadata for the bag itself is also stored.
|
|
186
|
+
We saw this in the GUI snapshot above, but it can also be accessed directly by code:
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
>>> boh.H5Bag.get_bag_info()
|
|
190
|
+
H5Info(qualname='H5Bag', module='bagofholding.h5.bag', version='...', libver_str='latest')
|
|
191
|
+
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
(In reality you will see a version code, it is omitted here because this example is executed automatically in the test suite.)
|
|
195
|
+
|
|
196
|
+
## Going further
|
|
197
|
+
|
|
198
|
+
For a more in-depth look at the above features and to explore other aspects of `bagofholding`, check out [the tutorial notebook](../notebooks/tutorial.ipynb).
|
|
199
|
+
|
|
200
|
+
Finally, `bagofholding` prioritizes transparency in what is stored and ease-of-use for both savers and loaders/browsers.
|
|
201
|
+
As such, the current hdf5-based implementation is likely to be significantly less performant than raw pickling, due to the creation of many small datasets that allow the h5 file to directly replicate the underlying structure of the python objects being saved.
|
|
202
|
+
For objects which contain large `numpy` arrays, this disadvantage is significantly alleviated as we benefit from the very efficient treatment of such arrays in hdf5 and `h5py`.
|
|
203
|
+
For all other objects, the current `bagofholding.H5Bag` is still an appropriate choice when the robustness of long term storage is more pressing than optimizing storage space.
|
|
204
|
+
Other bag types may be available in the future.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from . import _version
|
|
2
|
+
|
|
3
|
+
__version__ = _version.get_versions()["version"]
|
|
4
|
+
|
|
5
|
+
from bagofholding.exceptions import BagMismatchError as BagMismatchError
|
|
6
|
+
from bagofholding.exceptions import BagOfHoldingError as BagOfHoldingError
|
|
7
|
+
from bagofholding.exceptions import EnvironmentMismatchError as EnvironmentMismatchError
|
|
8
|
+
from bagofholding.exceptions import FileAlreadyOpenError as FileAlreadyOpenError
|
|
9
|
+
from bagofholding.exceptions import FileNotOpenError as FileNotOpenError
|
|
10
|
+
from bagofholding.exceptions import FilepathError as FilepathError
|
|
11
|
+
from bagofholding.exceptions import InvalidMetadataError as InvalidMetadataError
|
|
12
|
+
from bagofholding.exceptions import ModuleForbiddenError as ModuleForbiddenError
|
|
13
|
+
from bagofholding.exceptions import NotAGroupError as NotAGroupError
|
|
14
|
+
from bagofholding.exceptions import NoVersionError as NoVersionError
|
|
15
|
+
from bagofholding.exceptions import PickleProtocolError as PickleProtocolError
|
|
16
|
+
from bagofholding.exceptions import (
|
|
17
|
+
StringReductionNotImportableError as StringReductionNotImportableError,
|
|
18
|
+
)
|
|
19
|
+
from bagofholding.h5.bag import H5Bag as H5Bag
|
|
20
|
+
from bagofholding.h5.triebag import TrieH5Bag as TrieH5Bag
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
|
|
2
|
+
# This file was generated by 'versioneer.py' (0.29) from
|
|
3
|
+
# revision-control system data, or from the parent directory name of an
|
|
4
|
+
# unpacked source archive. Distribution tarballs contain a pre-generated copy
|
|
5
|
+
# of this file.
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
|
|
9
|
+
version_json = '''
|
|
10
|
+
{
|
|
11
|
+
"date": "2025-06-24T12:59:33-0700",
|
|
12
|
+
"dirty": true,
|
|
13
|
+
"error": null,
|
|
14
|
+
"full-revisionid": "c3a220f05f2113bd48df312462301dc600746de8",
|
|
15
|
+
"version": "0.post0.dev1"
|
|
16
|
+
}
|
|
17
|
+
''' # END VERSION_JSON
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_versions():
|
|
21
|
+
return json.loads(version_json)
|
|
@@ -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
|