json_write 0.0.1.3__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.
json_write/__init__.py ADDED
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env python3
2
+ # coding: utf-8
3
+
4
+ __author__ = "ChenyangGao <https://chenyanggao.github.io>"
5
+ __version__ = (0, 0, 1)
6
+ __all__ = [
7
+ "json_log_gen_write", "json_log_write", "json_array_gen_write", "json_array_write",
8
+ "json_object_gen_write", "json_object_write", "json_groups_gen_write", "json_groups_write",
9
+ "json_gen_write", "json_write", "json_ensure_gen_write", "json_ensure_write",
10
+ ]
11
+
12
+ from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
13
+ from contextlib import contextmanager
14
+ from functools import update_wrapper
15
+ from io import TextIOWrapper
16
+ from os import PathLike
17
+ from os.path import exists
18
+ from operator import itemgetter
19
+ from sys import stdout
20
+ from typing import Optional, Protocol, TypeAlias
21
+
22
+ dumps: Callable[..., bytes]
23
+ try:
24
+ from orjson import dumps
25
+ except ImportError:
26
+ _dumps: Callable[..., str]
27
+ try:
28
+ from ujson import dumps as _dumps
29
+ except ImportError:
30
+ from json import dumps as _dumps
31
+ dumps = lambda obj: _dumps(obj, ensure_ascii=False).encode("utf-8")
32
+
33
+
34
+ PathType: TypeAlias = bytes | str | PathLike
35
+
36
+
37
+ class SupportsWriteBytes(Protocol):
38
+ def write(self, s: bytes, /) -> object: ...
39
+
40
+
41
+ @contextmanager
42
+ def gen_as_ctx(gen: Generator, /):
43
+ try:
44
+ yield gen.send
45
+ finally:
46
+ gen.close()
47
+
48
+
49
+ def gen_startup(func, /):
50
+ def wrapper(*args, **kwds):
51
+ r = func(*args, **kwds)
52
+ next(r)
53
+ return r
54
+ return update_wrapper(wrapper, func)
55
+
56
+
57
+ def foreach(fn, it, /, *its):
58
+ if its:
59
+ for args in zip(it, *its):
60
+ fn(*args)
61
+ else:
62
+ for arg in it:
63
+ fn(arg)
64
+
65
+
66
+ @gen_startup
67
+ def json_log_gen_write(
68
+ value: Optional[Callable] = None,
69
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
70
+ ):
71
+ if isinstance(file, TextIOWrapper):
72
+ file = file.buffer
73
+ write = file.write
74
+ while True:
75
+ val = yield
76
+ if value is not None:
77
+ val = value(val)
78
+ write(dumps(val))
79
+ write(b"\n")
80
+
81
+
82
+ def json_log_write(
83
+ it: Iterable,
84
+ /,
85
+ value: Optional[Callable] = None,
86
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
87
+ ):
88
+ with gen_as_ctx(json_log_gen_write(value=value, file=file)) as write:
89
+ foreach(write, it)
90
+
91
+
92
+ @gen_startup
93
+ def json_array_gen_write(
94
+ value: Optional[Callable] = None,
95
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
96
+ ):
97
+ if isinstance(file, TextIOWrapper):
98
+ file = file.buffer
99
+ write = file.write
100
+ write(b"[")
101
+ try:
102
+ not_first = False
103
+ while True:
104
+ val = yield
105
+ if value is not None:
106
+ val = value(val)
107
+ if not_first:
108
+ write(b","+dumps(val))
109
+ else:
110
+ write(dumps(val))
111
+ not_first = True
112
+ finally:
113
+ write(b"]")
114
+
115
+
116
+ def json_array_write(
117
+ it: Iterable,
118
+ /,
119
+ value: Optional[Callable] = None,
120
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
121
+ ):
122
+ with gen_as_ctx(json_array_gen_write(value=value, file=file)) as write:
123
+ foreach(write, it)
124
+
125
+
126
+ @gen_startup
127
+ def json_object_gen_write(
128
+ key: Callable,
129
+ value: Optional[Callable] = None,
130
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
131
+ ):
132
+ if isinstance(file, TextIOWrapper):
133
+ file = file.buffer
134
+ write = file.write
135
+ write(b"{")
136
+ try:
137
+ not_first = False
138
+ while True:
139
+ val = yield
140
+ if value is not None:
141
+ val = value(val)
142
+ if not_first:
143
+ tpl = b",%s:%s"
144
+ else:
145
+ tpl = b"%s:%s"
146
+ not_first = True
147
+ write(tpl % (dumps(str(key(val))), dumps(val)))
148
+ finally:
149
+ write(b"}")
150
+
151
+
152
+ def json_object_write(
153
+ it: Iterable,
154
+ /,
155
+ key: Optional[Callable] = None,
156
+ value: Optional[Callable] = None,
157
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
158
+ ):
159
+ if key is None:
160
+ if isinstance(it, Mapping):
161
+ if hasattr(it, "items"):
162
+ it = it.items()
163
+ else:
164
+ it = ((k, it[k]) for k in it)
165
+ key = itemgetter(0)
166
+ if value is None:
167
+ value = itemgetter(1)
168
+ else:
169
+ value = lambda t, _val=value: _val(t[1])
170
+ with gen_as_ctx(json_object_gen_write(key, value=value, file=file)) as write:
171
+ foreach(write, it)
172
+
173
+
174
+ @gen_startup
175
+ def json_groups_gen_write(
176
+ keys: Sequence[Callable],
177
+ *,
178
+ value: Optional[Callable] = None,
179
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
180
+ ):
181
+ assert keys, "empty keys"
182
+ if isinstance(file, TextIOWrapper):
183
+ file = file.buffer
184
+ write = file.write
185
+ last_ks: tuple[bytes, ...] = ()
186
+ write(b"{")
187
+ try:
188
+ while True:
189
+ val = yield
190
+ if value is not None:
191
+ val = value(val)
192
+ ks = tuple(dumps(str(key(val))) for key in keys)
193
+ if last_ks:
194
+ for i, (k0, k1) in enumerate(zip(last_ks, ks)):
195
+ if k0 != k1:
196
+ break
197
+ ks2 = ks[i:-1]
198
+ if ks2:
199
+ write(b"}" * len(ks2))
200
+ write(b",")
201
+ else:
202
+ ks2 = ks[:-1]
203
+ for k in ks2:
204
+ write(b"%s:{" % k)
205
+ write(b"%s:%s" % (ks[-1], dumps(val)))
206
+ last_ks = ks
207
+ finally:
208
+ if last_ks:
209
+ write(b"}" * len(keys))
210
+ else:
211
+ write(b"}")
212
+
213
+
214
+ def json_groups_write(
215
+ it: Iterable,
216
+ /,
217
+ keys: Sequence[Callable],
218
+ value: Optional[Callable] = None,
219
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
220
+ ):
221
+ with gen_as_ctx(json_groups_gen_write(keys, value=value, file=file)) as write:
222
+ foreach(write, it)
223
+
224
+
225
+ def json_gen_write(
226
+ keys: None | Callable | Sequence[Callable] = None,
227
+ value: Optional[Callable] = None,
228
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
229
+ ):
230
+ if keys is None:
231
+ return json_log_gen_write(value=value, file=file)
232
+ elif callable(keys):
233
+ return json_object_gen_write(keys, value=value, file=file)
234
+ elif keys:
235
+ if len(keys) == 1:
236
+ return json_object_gen_write(keys[0], value=value, file=file)
237
+ return json_groups_gen_write(keys, value=value, file=file)
238
+ else:
239
+ return json_array_gen_write(value=value, file=file)
240
+
241
+
242
+ def json_write(
243
+ it: Iterable,
244
+ /,
245
+ keys: None | Callable | Sequence[Callable] = None,
246
+ value: Optional[Callable] = None,
247
+ file: SupportsWriteBytes | TextIOWrapper = stdout, # type: ignore
248
+ ):
249
+ with gen_as_ctx(json_gen_write(keys=keys, value=value, file=file)) as write:
250
+ foreach(write, it)
251
+
252
+
253
+ @gen_startup
254
+ def json_ensure_gen_write(
255
+ path: PathType,
256
+ key: Optional[Callable] = None,
257
+ value: Optional[Callable] = None,
258
+ resume: bool = False,
259
+ bufsize: int = -1,
260
+ ):
261
+ if bufsize <= 1:
262
+ bufsize = -1
263
+ if resume and exists(path):
264
+ f = open(path, "r+b", buffering=bufsize)
265
+ else:
266
+ f = open(path, "wb", buffering=bufsize)
267
+ seek = f.seek
268
+ write = f.write
269
+ not_first = seek(0, 2) >= 2
270
+ if not not_first:
271
+ seek(0)
272
+ if key is None:
273
+ while True:
274
+ val = yield
275
+ if value is not None:
276
+ val = value(val)
277
+ if not_first:
278
+ seek(-1, 1)
279
+ tpl = b",%s]"
280
+ else:
281
+ tpl = b"[%s]"
282
+ not_first = True
283
+ write(tpl % dumps(val))
284
+ else:
285
+ while True:
286
+ val = yield
287
+ if value is not None:
288
+ val = value(val)
289
+ if not_first:
290
+ seek(-1, 1)
291
+ tpl = b",%s:%s}"
292
+ else:
293
+ tpl = b"{%s:%s}"
294
+ not_first = True
295
+ write(tpl % (dumps(str(key(val))), dumps(val)))
296
+
297
+
298
+ def json_ensure_write(
299
+ it: Iterable,
300
+ /,
301
+ path: PathType,
302
+ key: Optional[Callable] = None,
303
+ value: Optional[Callable] = None,
304
+ resume: bool = False,
305
+ bufsize: int = -1,
306
+ ):
307
+ with gen_as_ctx(json_ensure_gen_write(
308
+ it,
309
+ path,
310
+ key=key,
311
+ value=value,
312
+ resume=resume,
313
+ bufsize=bufsize,
314
+ )) as write:
315
+ foreach(write, it)
316
+
json_write/py.typed ADDED
File without changes
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.4
2
+ Name: json_write
3
+ Version: 0.0.1.3
4
+ Summary: JSON write tools.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: json,write
8
+ Author: ChenyangGao
9
+ Author-email: wosiwujm@gmail.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3 :: Only
23
+ Classifier: Topic :: Software Development
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Project-URL: Homepage, https://github.com/ChenyangGao/python-modules/tree/main/json_write
27
+ Project-URL: Repository, https://github.com/ChenyangGao/python-modules/tree/main/json_write
28
+ Description-Content-Type: text/markdown
29
+
30
+ # JSON write tools
31
+
32
+ ## Installation
33
+
34
+ You can install from [pypi](https://pypi.org/project/json_write/)
35
+
36
+ ```console
37
+ pip install -U json_write
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ...
43
+
@@ -0,0 +1,6 @@
1
+ json_write/__init__.py,sha256=LzcC6lI9NJ-l507h-ACdVjW9UNcceg6fbOmN9SISLVc,8358
2
+ json_write/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ json_write-0.0.1.3.dist-info/METADATA,sha256=9fuE5m2_8P-rHXX96WvxdaSvelo3XelkNm51DhToprI,1375
4
+ json_write-0.0.1.3.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
5
+ json_write-0.0.1.3.dist-info/licenses/LICENSE,sha256=o5242_N2TgDsWwFhPn7yr8YJNF7XsJM5NxUMtcT97bc,1100
6
+ json_write-0.0.1.3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.4.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 ChenyangGao <https://github.com/ChenyangGao>
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.