swapcollection 1.0.0__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.
@@ -0,0 +1,3 @@
1
+ from .swapcollection import SwapDict, SwapList
2
+
3
+ __all__ = ["SwapDict", "SwapList"]
@@ -0,0 +1,234 @@
1
+ from sqlite_utils import Database
2
+ from sqlite_utils.db import NotFoundError
3
+ import uuid
4
+ from collections import UserDict, UserList
5
+ import pickle
6
+
7
+ class SwapDict(UserDict):
8
+ PREFIX = "swapdict_"
9
+ PATH = "swapcollections_cache.db"
10
+
11
+ def __init__(self, data={}, size_threshold: int = 1048576):
12
+ self.db = Database(self.PATH)
13
+ self.table = self.db["DICT"]
14
+ self.size_threshold = size_threshold
15
+
16
+ if not self.table.exists():
17
+ self.table.create(
18
+ {
19
+ "id": str,
20
+ "value": bytes,
21
+ },
22
+ pk="id",
23
+ )
24
+
25
+ super().__init__(data) # 内部で__setitem__を呼んで処理するので、ここでは何もしない
26
+
27
+ def _setprocess(self, value):
28
+ id = self.PREFIX + str(uuid.uuid4())
29
+ self.table.insert({"id": id, "value": pickle.dumps(value)})
30
+ return str(id)
31
+
32
+ def _getprocess(self, id):
33
+ result = self.table.get(id)
34
+ if result:
35
+ return pickle.loads(result["value"])
36
+ raise NotFoundError(f"id {id} not found")
37
+
38
+ def __setitem__(self, key, value):
39
+ if len(pickle.dumps(value)) >= self.size_threshold:
40
+ value = self._setprocess(value)
41
+ return super().__setitem__(key, value)
42
+
43
+ def __getitem__(self, key):
44
+ value = super().__getitem__(key)
45
+ if type(value) == str:
46
+ if value.startswith(self.PREFIX):
47
+ return self._getprocess(value)
48
+ return value
49
+
50
+ def __repr__(self):
51
+ self.repr_data = UserDict()
52
+ for key, value in self.items():
53
+ if type(value) == str:
54
+ if value.startswith(self.PREFIX):
55
+ value = self._getprocess(value)
56
+ self.repr_data[key] = value
57
+ return repr(self.repr_data)
58
+
59
+ class SwapList(UserList):
60
+ PREFIX = "swaplist_"
61
+ PATH = "swapcollections_cache.db"
62
+
63
+ def __init__(self, data=None, size_threshold: int = 1048576):
64
+ self.db = Database(self.PATH)
65
+ self.table = self.db["LIST"]
66
+ self.size_threshold = size_threshold
67
+
68
+ if not self.table.exists():
69
+ self.table.create(
70
+ {
71
+ "id": str,
72
+ "value": bytes,
73
+ },
74
+ pk="id",
75
+ )
76
+
77
+ tmp_data = []
78
+ for i in (data or []):
79
+ if len(pickle.dumps(i)) >= self.size_threshold:
80
+ i = self._setprocess(i)
81
+ tmp_data.append(i)
82
+
83
+ super().__init__(tmp_data)
84
+
85
+ def _setprocess(self, value):
86
+ id = self.PREFIX + str(uuid.uuid4())
87
+ self.table.insert({"id": id, "value": pickle.dumps(value)})
88
+ return id
89
+
90
+ def _getprocess(self, id):
91
+ result = self.table.get(id)
92
+ if result:
93
+ return pickle.loads(result["value"])
94
+ raise NotFoundError(f"id {id} not found")
95
+
96
+ def __setitem__(self, i, value):
97
+ if isinstance(i, slice):
98
+ processed = []
99
+ for v in value:
100
+ if len(pickle.dumps(v)) >= self.size_threshold:
101
+ v = self._setprocess(v)
102
+ processed.append(v)
103
+ return super().__setitem__(i, processed)
104
+ if len(pickle.dumps(value)) >= self.size_threshold:
105
+ value = self._setprocess(value)
106
+ return super().__setitem__(i, value)
107
+
108
+ def __eq__(self, other):
109
+ try:
110
+ return list(self) == list(other)
111
+ except TypeError:
112
+ return NotImplemented
113
+
114
+ def __getitem__(self, i):
115
+ value = super().__getitem__(i)
116
+ if type(value) == str:
117
+ if value.startswith(self.PREFIX):
118
+ return self._getprocess(value)
119
+ return value
120
+
121
+ def _resolve(self, value):
122
+ """Return the original value if it's a spill ID, otherwise return as-is."""
123
+ if isinstance(value, str) and value.startswith(self.PREFIX):
124
+ return self._getprocess(value)
125
+ return value
126
+
127
+ def __contains__(self, item):
128
+ for i in range(len(self)):
129
+ if self[i] == item:
130
+ return True
131
+ return False
132
+
133
+ def pop(self, i=-1):
134
+ resolved = self[i]
135
+ self.data.pop(i)
136
+ return resolved
137
+
138
+ def index(self, item, *args):
139
+ start = args[0] if len(args) > 0 else 0
140
+ stop = args[1] if len(args) > 1 else len(self)
141
+ for i in range(start, stop):
142
+ if self[i] == item:
143
+ return i
144
+ raise ValueError(f"{item!r} is not in list")
145
+
146
+ def count(self, item):
147
+ cnt = 0
148
+ for i in range(len(self)):
149
+ if self[i] == item:
150
+ cnt += 1
151
+ return cnt
152
+
153
+ def remove(self, item):
154
+ idx = self.index(item)
155
+ del self[idx]
156
+
157
+ def sort(self, *args, **kwds):
158
+ resolved = [self._resolve(v) for v in self.data]
159
+ resolved.sort(*args, **kwds)
160
+ self.data.clear()
161
+ for value in resolved:
162
+ if len(pickle.dumps(value)) >= self.size_threshold:
163
+ value = self._setprocess(value)
164
+ self.data.append(value)
165
+
166
+ def append(self, value):
167
+ if len(pickle.dumps(value)) >= self.size_threshold:
168
+ value = self._setprocess(value)
169
+ return super().append(value)
170
+
171
+ def extend(self, value):
172
+ tmp_value = []
173
+ for i in value:
174
+ if len(pickle.dumps(i)) >= self.size_threshold:
175
+ i = self._setprocess(i)
176
+ tmp_value.append(i)
177
+ return super().extend(tmp_value)
178
+
179
+ def __repr__(self):
180
+ self.repr_data = UserList()
181
+ for i in self:
182
+ if type(i) == str:
183
+ if i.startswith(self.PREFIX):
184
+ i = self._getprocess(i)
185
+ self.repr_data.append(i)
186
+ return repr(self.repr_data)
187
+
188
+ if __name__ == "__main__":
189
+
190
+ class TestObj:
191
+ def __init__(self, a, b):
192
+ self.a = a
193
+ self.b = b
194
+ self.c = a + b
195
+
196
+ def test(self):
197
+ return self.c
198
+
199
+ testobj = TestObj(1, 2)
200
+
201
+ tmp = SwapList(
202
+ [
203
+ "hello",
204
+ {"hello": "world"},
205
+ testobj,
206
+ 1977,
207
+ ],
208
+ size_threshold=1,
209
+ )
210
+
211
+ tmp.append("hello")
212
+ tmp.extend([{"hello": "world"}, testobj, 1977])
213
+ tmp[2:4] = ["hello", {"hello": "world"}, testobj, 1977]
214
+ print(tmp)
215
+
216
+
217
+ for i in tmp:
218
+ print(i)
219
+
220
+ # tmp2 = SwapList(
221
+ # [
222
+ # "small",
223
+ # {"hello": "world"},
224
+ # "large",
225
+ # {"hello": "world", "hello": "world", "hello": "world"},
226
+ # ],
227
+ # size_threshold=1,
228
+ # )
229
+
230
+ # print(tmp2)
231
+ # print(tmp2[0])
232
+ # print(tmp2[1])
233
+ # print(tmp2[2])
234
+ # print(tmp2[3])
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: swapcollection
3
+ Version: 1.0.0
4
+ Summary: A library that automatically offloads large pickle-able objects stored in a dict/list to SQLite, reducing memory usage. It can be used with the same syntax as a regular dict/list.
5
+ Author: llinghyami
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/llinghyami/swapcollection
8
+ Project-URL: Repository, https://github.com/llinghyami/swapcollection.git
9
+ Classifier: Programming Language :: Python :: 3
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: sqlite-utils
14
+ Dynamic: license-file
15
+
16
+ > **English** · [日本語 (Japanese)](README.md)
17
+
18
+ # swapcollection
19
+
20
+ A library that automatically offloads large objects stored in a
21
+ `dict`/`list` to SQLite, reducing memory usage. It can be used with
22
+ the same syntax as a regular `dict`/`list`.
23
+
24
+ ## Quick Start
25
+
26
+ ```bash
27
+ pip install swapcollection
28
+ ```
29
+
30
+ ```python
31
+ from swapcollection import SwapDict, SwapList
32
+
33
+ # Spill values >= 1 MB (pickle size) to SQLite
34
+ data = SwapDict(size_threshold=1024)
35
+
36
+ data["small"] = b"hello"
37
+ data["large"] = b"x" * 100_000
38
+
39
+ # Access transparently — same as a normal dict
40
+ print(data["small"])
41
+ print(len(data["large"]))
42
+ ```
43
+
44
+ ## How It Works
45
+
46
+ `SwapDict` / `SwapList` automatically offloads values whose pickled size
47
+ meets or exceeds `size_threshold` to a SQLite database. Any pickle-able
48
+ object (not just `bytes`) is eligible.
49
+
50
+ | Value | Storage |
51
+ |---|---|
52
+ | Pickle size < `size_threshold` | In-memory |
53
+ | Pickle size >= `size_threshold` | SQLite (transparent) |
54
+
55
+ Spilled values are retrieved, updated, and deleted using the same `dict`/`list`
56
+ interface — no special API calls needed.
57
+
58
+ ## Caveats
59
+
60
+ - `size_threshold` is the pickle-size threshold in bytes; values >= this size
61
+ are spilled.
62
+ - `size_threshold` cannot be changed after instantiation.
63
+ - Any pickle-able object type (not only `bytes`) can be spilled.
64
+ - Deleting the SQLite database will cause errors on previously spilled items.
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,7 @@
1
+ swapcollection/__init__.py,sha256=OXj6fYQu7-Bj-Msmx3f1O7K6VubrOTWtEE4isSshR-s,83
2
+ swapcollection/swapcollection.py,sha256=-Dp_SD1uqqUdEpbmWPjU2nsTEVYo7acTgx_NGoe_tR8,6769
3
+ swapcollection-1.0.0.dist-info/licenses/LICENSE,sha256=BM5MwGCc7-gpyfEiiWcqbmDcpyTVco9NLSM6uY-adu4,1067
4
+ swapcollection-1.0.0.dist-info/METADATA,sha256=n8fyltJ3mQ0_Hr0FDZ0KKC4pZlAeCQ2WGXKWaIZ2kKk,2006
5
+ swapcollection-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
6
+ swapcollection-1.0.0.dist-info/top_level.txt,sha256=XB7bFNMYsk7b4MZP9yexv2oEMPofADUvpZ_qUCnscvw,15
7
+ swapcollection-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 renren5977
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ swapcollection