swapcollection 1.0.0__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.
@@ -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,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,53 @@
1
+ > **English** · [日本語 (Japanese)](README.md)
2
+
3
+ # swapcollection
4
+
5
+ A library that automatically offloads large objects stored in a
6
+ `dict`/`list` to SQLite, reducing memory usage. It can be used with
7
+ the same syntax as a regular `dict`/`list`.
8
+
9
+ ## Quick Start
10
+
11
+ ```bash
12
+ pip install swapcollection
13
+ ```
14
+
15
+ ```python
16
+ from swapcollection import SwapDict, SwapList
17
+
18
+ # Spill values >= 1 MB (pickle size) to SQLite
19
+ data = SwapDict(size_threshold=1024)
20
+
21
+ data["small"] = b"hello"
22
+ data["large"] = b"x" * 100_000
23
+
24
+ # Access transparently — same as a normal dict
25
+ print(data["small"])
26
+ print(len(data["large"]))
27
+ ```
28
+
29
+ ## How It Works
30
+
31
+ `SwapDict` / `SwapList` automatically offloads values whose pickled size
32
+ meets or exceeds `size_threshold` to a SQLite database. Any pickle-able
33
+ object (not just `bytes`) is eligible.
34
+
35
+ | Value | Storage |
36
+ |---|---|
37
+ | Pickle size < `size_threshold` | In-memory |
38
+ | Pickle size >= `size_threshold` | SQLite (transparent) |
39
+
40
+ Spilled values are retrieved, updated, and deleted using the same `dict`/`list`
41
+ interface — no special API calls needed.
42
+
43
+ ## Caveats
44
+
45
+ - `size_threshold` is the pickle-size threshold in bytes; values >= this size
46
+ are spilled.
47
+ - `size_threshold` cannot be changed after instantiation.
48
+ - Any pickle-able object type (not only `bytes`) can be spilled.
49
+ - Deleting the SQLite database will cause errors on previously spilled items.
50
+
51
+ ## License
52
+
53
+ MIT
@@ -0,0 +1,48 @@
1
+ > [English (English)](README.en.md) · **日本語**
2
+
3
+ # swapcollection
4
+
5
+ 辞書型やリストに格納された大容量のオブジェクトを自動的にSQLiteへ退避し、メモリ使用量を削減するライブラリです。通常の `dict` / `list` と同じ書き方で使用できます。
6
+
7
+ ## クイックスタート
8
+
9
+ ```bash
10
+ pip install swapcollection
11
+ ```
12
+
13
+ ```python
14
+ from swapcollection import SwapDict, SwapList
15
+
16
+ # 1 MB以上の値をSQLiteへ退避
17
+ data = SwapDict(size_threshold=1024)
18
+
19
+ data["small"] = b"hello"
20
+ data["large"] = b"x" * 100_000
21
+
22
+ # 通常のdictと同じように取得
23
+ print(data["small"])
24
+ print(len(data["large"]))
25
+ ```
26
+
27
+ ## 仕組み
28
+
29
+ `SwapDict` / `SwapList` は、格納された値を pickle したサイズが `size_threshold` 以上の場合に、値をSQLiteへ自動的に退避します。`bytes` に限らず、任意のpickle可能なオブジェクトが対象です。
30
+
31
+ | 値 | 保存先 |
32
+ |---|---|
33
+ | pickleサイズ < `size_threshold` | メモリ |
34
+ | pickleサイズ >= `size_threshold` | SQLite |
35
+
36
+ SQLiteへ退避された値も、通常の `dict` / `list` と同じ方法で取得、更新、削除できます。
37
+
38
+ ## 注意事項
39
+
40
+ - `size_threshold` は、SQLiteへ退避する pickle サイズの閾値をバイト単位で指定します。
41
+ - サイズが `size_threshold` と等しい値もSQLiteへ退避されます。
42
+ - `size_threshold` はインスタンス作成後に変更できません。
43
+ - 値の種類(`bytes` 以外も含む)は pickle サイズでのみ判断されます。
44
+ - SQLiteデータベースを削除すると、退避済みの値を取得できなくなり、エラーが発生します。
45
+
46
+ ## ライセンス
47
+
48
+ MIT
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "swapcollection"
7
+ version = "1.0.0"
8
+ description = "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."
9
+ readme = "README.en.md"
10
+ license = "MIT"
11
+ authors = [
12
+ {name = "llinghyami"},
13
+ ]
14
+ requires-python = ">=3.10"
15
+ dependencies = [
16
+ "sqlite-utils",
17
+ ]
18
+ classifiers = [
19
+ "Programming Language :: Python :: 3",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/llinghyami/swapcollection"
24
+ Repository = "https://github.com/llinghyami/swapcollection.git"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["."]
28
+ include = ["swapcollection*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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,13 @@
1
+ LICENSE
2
+ README.en.md
3
+ README.md
4
+ pyproject.toml
5
+ swapcollection/__init__.py
6
+ swapcollection/swapcollection.py
7
+ swapcollection.egg-info/PKG-INFO
8
+ swapcollection.egg-info/SOURCES.txt
9
+ swapcollection.egg-info/dependency_links.txt
10
+ swapcollection.egg-info/requires.txt
11
+ swapcollection.egg-info/top_level.txt
12
+ tests/test_eq_comprehensive.py
13
+ tests/test_swapcollection.py
@@ -0,0 +1 @@
1
+ sqlite-utils
@@ -0,0 +1 @@
1
+ swapcollection