cs-seq 20250103__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 @@
1
+ include README.md
@@ -0,0 +1,399 @@
1
+ Metadata-Version: 2.1
2
+ Name: cs-seq
3
+ Version: 20250103
4
+ Summary: Stuff to do with counters, sequences and iterables.
5
+ Author-email: Cameron Simpson <cs@cskk.id.au>
6
+ License: GNU General Public License v3 or later (GPLv3+)
7
+ Project-URL: Monorepo Hg/Mercurial Mirror, https://hg.sr.ht/~cameron-simpson/css
8
+ Project-URL: Monorepo Git Mirror, https://github.com/cameron-simpson/css
9
+ Project-URL: MonoRepo Commits, https://bitbucket.org/cameron_simpson/css/commits/branch/main
10
+ Project-URL: Source, https://github.com/cameron-simpson/css/blob/main/lib/python/cs/seq.py
11
+ Keywords: python2,python3
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 2
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: cs.deco>=20250103
22
+ Requires-Dist: cs.gimmicks>=20240316
23
+
24
+ Stuff to do with counters, sequences and iterables.
25
+
26
+ *Latest release 20250103*:
27
+ New skip_map(func, *iterables, except_types, quiet=False) generator function, like map() but skipping certain exceptions.
28
+
29
+ Note that any function accepting an iterable
30
+ will consume some or all of the derived iterator
31
+ in the course of its function.
32
+
33
+ ## <a name="common_prefix_length"></a>`common_prefix_length(*seqs)`
34
+
35
+ Return the length of the common prefix of sequences `seqs`.
36
+
37
+ ## <a name="common_suffix_length"></a>`common_suffix_length(*seqs)`
38
+
39
+ Return the length of the common suffix of sequences `seqs`.
40
+
41
+ ## <a name="first"></a>`first(iterable)`
42
+
43
+ Return the first item from an iterable; raise `IndexError` on empty iterables.
44
+
45
+ ## <a name="get0"></a>`get0(iterable, default=None)`
46
+
47
+ Return first element of an iterable, or the default.
48
+
49
+ ## <a name="greedy"></a>`greedy(g=None, queue_depth=0)`
50
+
51
+ A decorator or function for greedy computation of iterables.
52
+
53
+ If `g` is omitted or callable
54
+ this is a decorator for a generator function
55
+ causing it to compute greedily,
56
+ capacity limited by `queue_depth`.
57
+
58
+ If `g` is iterable
59
+ this function dispatches it in a `Thread` to compute greedily,
60
+ capacity limited by `queue_depth`.
61
+
62
+ Example with an iterable:
63
+
64
+ for packet in greedy(parse_data_stream(stream)):
65
+ ... process packet ...
66
+
67
+ which does some readahead of the stream.
68
+
69
+ Example as a function decorator:
70
+
71
+ @greedy
72
+ def g(n):
73
+ for item in range(n):
74
+ yield n
75
+
76
+ This can also be used directly on an existing iterable:
77
+
78
+ for item in greedy(range(n)):
79
+ yield n
80
+
81
+ Normally a generator runs on demand.
82
+ This function dispatches a `Thread` to run the iterable
83
+ (typically a generator)
84
+ putting yielded values to a queue
85
+ and returns a new generator yielding from the queue.
86
+
87
+ The `queue_depth` parameter specifies the depth of the queue
88
+ and therefore how many values the original generator can compute
89
+ before blocking at the queue's capacity.
90
+
91
+ The default `queue_depth` is `0` which creates a `Channel`
92
+ as the queue - a zero storage buffer - which lets the generator
93
+ compute only a single value ahead of time.
94
+
95
+ A larger `queue_depth` allocates a `Queue` with that much storage
96
+ allowing the generator to compute as many as `queue_depth+1` values
97
+ ahead of time.
98
+
99
+ Here's a comparison of the behaviour:
100
+
101
+ Example without `@greedy`
102
+ where the "yield 1" step does not occur until after the "got 0":
103
+
104
+ >>> from time import sleep
105
+ >>> def g():
106
+ ... for i in range(2):
107
+ ... print("yield", i)
108
+ ... yield i
109
+ ... print("g done")
110
+ ...
111
+ >>> G = g(); sleep(0.1)
112
+ >>> for i in G:
113
+ ... print("got", i)
114
+ ... sleep(0.1)
115
+ ...
116
+ yield 0
117
+ got 0
118
+ yield 1
119
+ got 1
120
+ g done
121
+
122
+ Example with `@greedy`
123
+ where the "yield 1" step computes before the "got 0":
124
+
125
+ >>> from time import sleep
126
+ >>> @greedy
127
+ ... def g():
128
+ ... for i in range(2):
129
+ ... print("yield", i)
130
+ ... yield i
131
+ ... print("g done")
132
+ ...
133
+ >>> G = g(); sleep(0.1)
134
+ yield 0
135
+ >>> for i in G:
136
+ ... print("got", repr(i))
137
+ ... sleep(0.1)
138
+ ...
139
+ yield 1
140
+ got 0
141
+ g done
142
+ got 1
143
+
144
+ Example with `@greedy(queue_depth=1)`
145
+ where the "yield 1" step computes before the "got 0":
146
+
147
+ >>> from cs.x import X
148
+ >>> from time import sleep
149
+ >>> @greedy
150
+ ... def g():
151
+ ... for i in range(3):
152
+ ... X("Y")
153
+ ... print("yield", i)
154
+ ... yield i
155
+ ... print("g done")
156
+ ...
157
+ >>> G = g(); sleep(2)
158
+ yield 0
159
+ yield 1
160
+ >>> for i in G:
161
+ ... print("got", repr(i))
162
+ ... sleep(0.1)
163
+ ...
164
+ yield 2
165
+ got 0
166
+ yield 3
167
+ got 1
168
+ g done
169
+ got 2
170
+
171
+ ## <a name="imerge"></a>`imerge(*iters, **kw)`
172
+
173
+ Merge an iterable of ordered iterables in order.
174
+
175
+ Parameters:
176
+ * `iters`: an iterable of iterators
177
+ * `reverse`: keyword parameter: if true, yield items in reverse order.
178
+ This requires the iterables themselves to also be in
179
+ reversed order.
180
+
181
+ This function relies on the source iterables being ordered
182
+ and their elements being comparable, through slightly misordered
183
+ iterables (for example, as extracted from web server logs)
184
+ will produce only slightly misordered results, as the merging
185
+ is done on the basis of the front elements of each iterable.
186
+
187
+ ## <a name="isordered"></a>`isordered(items, reverse=False, strict=False)`
188
+
189
+ Test whether an iterable is ordered.
190
+ Note that the iterable is iterated, so this is a destructive
191
+ test for nonsequences.
192
+
193
+ ## <a name="last"></a>`last(iterable)`
194
+
195
+ Return the last item from an iterable; raise `IndexError` on empty iterables.
196
+
197
+ ## <a name="onetomany"></a>`onetomany(func)`
198
+
199
+ A decorator for a method of a sequence to merge the results of
200
+ passing every element of the sequence to the function, expecting
201
+ multiple values back.
202
+
203
+ Example:
204
+
205
+ class X(list):
206
+ @onetomany
207
+ def chars(self, item):
208
+ return item
209
+ strs = X(['Abc', 'Def'])
210
+ all_chars = X.chars()
211
+
212
+ ## <a name="onetoone"></a>`onetoone(func)`
213
+
214
+ A decorator for a method of a sequence to merge the results of
215
+ passing every element of the sequence to the function, expecting a
216
+ single value back.
217
+
218
+ Example:
219
+
220
+ class X(list):
221
+ @onetoone
222
+ def lower(self, item):
223
+ return item.lower()
224
+ strs = X(['Abc', 'Def'])
225
+ lower_strs = X.lower()
226
+
227
+ ## <a name="Seq"></a>Class `Seq`
228
+
229
+ A numeric sequence implemented as a thread safe wrapper for
230
+ `itertools.count()`.
231
+
232
+ A `Seq` is iterable and both iterating and calling it return
233
+ the next number in the sequence.
234
+
235
+ ## <a name="seq"></a>`seq()`
236
+
237
+ Return a new sequential value.
238
+
239
+ ## <a name="skip_map"></a>`skip_map(func, *iterables, except_types, quiet=False)`
240
+
241
+ A version of `map()` which will skip items where `func(item)`
242
+ raises an exception in `except_types`, a tuple of exception types.
243
+ If a skipped exception occurs a warning will be issued unless
244
+ `quiet` is true (default `False`).
245
+
246
+ ## <a name="splitoff"></a>`splitoff(sq, *sizes)`
247
+
248
+ Split a sequence into (usually short) prefixes and a tail,
249
+ for example to construct subdirectory trees based on a UUID.
250
+
251
+ Example:
252
+
253
+ >>> from uuid import UUID
254
+ >>> uuid = 'd6d9c510-785c-468c-9aa4-b7bda343fb79'
255
+ >>> uu = UUID(uuid).hex
256
+ >>> uu
257
+ 'd6d9c510785c468c9aa4b7bda343fb79'
258
+ >>> splitoff(uu, 2, 2)
259
+ ['d6', 'd9', 'c510785c468c9aa4b7bda343fb79']
260
+
261
+ ## <a name="StatefulIterator"></a>Class `StatefulIterator`
262
+
263
+ A trivial iterator which wraps another iterator to expose some tracking state.
264
+
265
+ This has 2 attributes:
266
+ * `.it`: the internal iterator which should yield `(item,new_state)`
267
+ * `.state`: the last state value from the internal iterator
268
+
269
+ The originating use case is resuse of an iterator by independent
270
+ calls that are typically sequential, specificly the .read
271
+ method of file like objects. Naive sequential reads require
272
+ the underlying storage to locate the data on every call, even
273
+ though the previous call has just performed this task for the
274
+ previous read. Saving the iterator used from the preceeding
275
+ call allows the iterator to pick up directly if the file
276
+ offset hasn't been fiddled in the meantime.
277
+
278
+ ## <a name="tee"></a>`tee(iterable, *Qs)`
279
+
280
+ A generator yielding the items from an iterable
281
+ which also copies those items to a series of queues.
282
+
283
+ Parameters:
284
+ * `iterable`: the iterable to copy
285
+ * `Qs`: the queues, objects accepting a `.put` method.
286
+
287
+ Note: the item is `.put` onto every queue
288
+ before being yielded from this generator.
289
+
290
+ ## <a name="the"></a>`the(iterable, context=None)`
291
+
292
+ Returns the first element of an iterable, but requires there to be
293
+ exactly one.
294
+
295
+ ## <a name="TrackingCounter"></a>Class `TrackingCounter`
296
+
297
+ A wrapper for a counter which can be incremented and decremented.
298
+
299
+ A facility is provided to wait for the counter to reach a specific value.
300
+ The .inc and .dec methods also accept a `tag` argument to keep
301
+ individual counts based on the tag to aid debugging.
302
+
303
+ TODO: add `strict` option to error and abort if any counter tries
304
+ to go below zero.
305
+
306
+ *`TrackingCounter.__init__(self, value=0, name=None, lock=None)`*:
307
+ Initialise the counter to `value` (default 0) with the optional `name`.
308
+
309
+ *`TrackingCounter.check(self)`*:
310
+ Internal consistency check.
311
+
312
+ *`TrackingCounter.dec(self, tag=None)`*:
313
+ Decrement the counter.
314
+ Wake up any threads waiting for its new value.
315
+
316
+ *`TrackingCounter.inc(self, tag=None)`*:
317
+ Increment the counter.
318
+ Wake up any threads waiting for its new value.
319
+
320
+ *`TrackingCounter.wait(self, value)`*:
321
+ Wait for the counter to reach the specified `value`.
322
+
323
+ ## <a name="unrepeated"></a>`unrepeated(it, seen=None, signature=None)`
324
+
325
+ A generator yielding items from the iterable `it` with no repetitions.
326
+
327
+ Parameters:
328
+ * `it`: the iterable to process
329
+ * `seen`: an optional setlike container supporting `in` and `.add()`
330
+ * `signature`: an optional signature function for items from `it`
331
+ which produces the value to compare to recognise repeated items;
332
+ its values are stored in the `seen` set
333
+
334
+ The default `signature` function is equality;
335
+ the items are stored n `seen` and compared.
336
+ This requires the items to be hashable and support equality tests.
337
+ The same applies to whatever values the `signature` function produces.
338
+
339
+ Another common signature is identity: `id`, useful for
340
+ traversing a graph which may have cycles.
341
+
342
+ Since `seen` accrues all the signature values for yielded items
343
+ generally it will grow monotonicly as iteration proceeeds.
344
+ If the items are complex or large it is well worth providing a signature
345
+ function even if the items themselves can be used in a set.
346
+
347
+ # Release Log
348
+
349
+
350
+
351
+ *Release 20250103*:
352
+ New skip_map(func, *iterables, except_types, quiet=False) generator function, like map() but skipping certain exceptions.
353
+
354
+ *Release 20221118*:
355
+ Small doc improvement.
356
+
357
+ *Release 20220530*:
358
+ Seq: calling a Seq is like next(seq).
359
+
360
+ *Release 20210924*:
361
+ New greedy(iterable) or @greedy(generator_function) to let generators precompute.
362
+
363
+ *Release 20210913*:
364
+ New unrepeated() generator removing duplicates from an iterable.
365
+
366
+ *Release 20201025*:
367
+ New splitoff() function to split a sequence into (usually short) prefixes and a tail.
368
+
369
+ *Release 20200914*:
370
+ New common_prefix_length and common_suffix_length for comparing prefixes and suffixes of sequences.
371
+
372
+ *Release 20190103*:
373
+ Documentation update.
374
+
375
+ *Release 20190101*:
376
+ * New and UNTESTED class StatefulIterator to associate some externally visible state with an iterator.
377
+ * Seq: accept optional `lock` parameter.
378
+
379
+ *Release 20171231*:
380
+ * Python 2 backport for imerge().
381
+ * New tee function to duplicate an iterable to queues.
382
+ * Function isordered() is now a test instead of an assertion.
383
+ * Drop NamedTuple, NamedTupleClassFactory (unused).
384
+
385
+ *Release 20160918*:
386
+ * New function isordered() to test ordering of a sequence.
387
+ * imerge: accept new `reverse` parameter for merging reversed iterables.
388
+
389
+ *Release 20160828*:
390
+ Modify DISTINFO to say "install_requires", fixes pypi requirements.
391
+
392
+ *Release 20160827*:
393
+ TrackingCounter: accept presupplied lock object. Python 3 exec fix.
394
+
395
+ *Release 20150118*:
396
+ metadata update
397
+
398
+ *Release 20150111*:
399
+ Initial PyPI release.