flpit 0.3.1.dev6__tar.gz → 0.3.2__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.
- {flpit-0.3.1.dev6 → flpit-0.3.2}/PKG-INFO +74 -8
- {flpit-0.3.1.dev6 → flpit-0.3.2}/README.md +73 -7
- {flpit-0.3.1.dev6 → flpit-0.3.2}/pyproject.toml +1 -1
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/__init__.py +6 -0
- flpit-0.3.2/src/flpit/core/_index.py +13 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/core/_join.py +1 -1
- flpit-0.3.2/src/flpit/core/_lookup.py +40 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/core/linq.py +447 -9
- {flpit-0.3.1.dev6 → flpit-0.3.2}/.gitignore +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/LICENSE +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flp/__init__.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/core/__init__.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/core/_grouping.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/core/_zip.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/csv.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/flp.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/json.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/py.typed +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/task.py +0 -0
- {flpit-0.3.1.dev6 → flpit-0.3.2}/src/flpit/threading.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flpit
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Fluent LINQ for Python — flip your iterables
|
|
5
5
|
Project-URL: Homepage, https://github.com/riemar/flpit
|
|
6
6
|
Project-URL: Repository, https://github.com/riemar/flpit
|
|
@@ -273,6 +273,38 @@ list(FlpList([1, 2, 2, 3])).count(2) # 2
|
|
|
273
273
|
|
|
274
274
|
This behavior is a core part of `FlpList`'s LINQ-oriented contract, not an incomplete `list` implementation.
|
|
275
275
|
|
|
276
|
+
## Indexed Elements: `index()`
|
|
277
|
+
|
|
278
|
+
`index()` is the **.NET 9 `Index()` operator**. It pairs every element with its zero-based position and yields `IndexTuple(index, item)`. `IndexTuple` is a `NamedTuple`, so it unpacks and compares like a plain `(index, item)` tuple:
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
flp.it(["a", "b", "c"]).index()
|
|
282
|
+
# [(0, "a"), (1, "b"), (2, "c")] (.NET 9 Index)
|
|
283
|
+
|
|
284
|
+
for i, name in flp.it(["a", "b"]).index():
|
|
285
|
+
...
|
|
286
|
+
|
|
287
|
+
flp.it(names).index().where(lambda t: t.index % 2 == 0).select(lambda t: t.item)
|
|
288
|
+
# every second name, starting with the first
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
* Execution is deferred and the source is streamed element by element; nothing is buffered.
|
|
292
|
+
* The .NET `OverflowException` after `int.MaxValue` elements does not apply: Python integers do not overflow.
|
|
293
|
+
|
|
294
|
+
### No indexed `select()` / `where()` overloads
|
|
295
|
+
|
|
296
|
+
.NET also offers `Select((item, index) => ...)` and `Where((item, index) => ...)`.
|
|
297
|
+
With `index()` available, these overloads are **not planned** for `select()` and `where()`.
|
|
298
|
+
This is a consequence of the Python runtime rather than an oversight: .NET picks between `x => ...` and `(x, i) => ...` at compile time through overload resolution,
|
|
299
|
+
but Python has no overloads at runtime. A method receives one callable, and the only way to tell the two shapes apart would be to inspect that callable's signature on every call.
|
|
300
|
+
That is fragile (builtins, `functools.partial`, `*args`, C-implemented callables) and would make behavior depend on how a function happens to be written.
|
|
301
|
+
Keeping a single, unambiguous signature per operator and composing with `index()` expresses the same thing explicitly:
|
|
302
|
+
|
|
303
|
+
```python
|
|
304
|
+
flp.it(source).index().select(lambda t: f"{t.index}: {t.item}") # instead of Select((x, i) => ...)
|
|
305
|
+
flp.it(source).index().where(lambda t: t.index >= 2).select(lambda t: t.item) # instead of Where((x, i) => ...)
|
|
306
|
+
```
|
|
307
|
+
|
|
276
308
|
## 🔗 Independent Query Pipelines
|
|
277
309
|
|
|
278
310
|
Query pipelines can be composed independently without mutating the queries they were derived from:
|
|
@@ -324,15 +356,23 @@ flp.it(customers).left_join(orders, lambda c: c[1], lambda o: o[1], lambda c, o:
|
|
|
324
356
|
# [("Prakash", 10), ("Prakash", 11), ("Tim", None), ("Robert", None)] (.NET 10 LeftJoin)
|
|
325
357
|
|
|
326
358
|
flp.it(customers).full_join(orders, lambda c: c[1], lambda o: o[1], lambda c, o: (c and c[0], o and o[0]))
|
|
327
|
-
# [("Prakash", 10), ("Prakash", 11), ("Tim", None), ("Robert", None), (None, 12)]
|
|
359
|
+
# [("Prakash", 10), ("Prakash", 11), ("Tim", None), ("Robert", None), (None, 12)] (.NET 11 FullJoin)
|
|
360
|
+
|
|
361
|
+
flp.it(customers).group_join(orders, lambda c: c[1], lambda o: o[1], lambda c, os: (c[0], os.select(lambda o: o[0]).to_list()))
|
|
362
|
+
# [("Prakash", [10, 11]), ("Tim", []), ("Robert", [])] group join (.NET GroupJoin)
|
|
363
|
+
|
|
364
|
+
flp.it([1, 2]).cross_join(["a", "b"], lambda n, c: f"{n}{c}")
|
|
365
|
+
# ["1a", "1b", "2a", "2b"] cross join (no .NET equivalent)
|
|
328
366
|
```
|
|
329
367
|
|
|
330
|
-
Without a result selector
|
|
368
|
+
Without a result selector `join()`, `left_join()`, `full_join()` and `cross_join()` yield `JoinTuple(outer, inner)`; `group_join()` yields a `Grouping` whose `key` is the outer element and whose items are its matching inner elements.
|
|
331
369
|
|
|
332
|
-
* Elements whose key is `None` never match. `left_join()` / `full_join()` still emit them as unmatched.
|
|
370
|
+
* Elements whose key is `None` never match. `left_join()` / `full_join()` still emit them as unmatched; `group_join()` still emits them with an empty group.
|
|
333
371
|
* An unmatched side is passed to the result selector as `None` (the Python equivalent of .NET `default`).
|
|
334
|
-
* `full_join()`
|
|
335
|
-
*
|
|
372
|
+
* `full_join()` follows .NET 11 `FullJoin` (`join()` / `left_join()` follow .NET 10 and earlier). It yields the `left_join()` rows in outer order, followed by every inner element that was never matched (in inner order).
|
|
373
|
+
* `group_join()` follows .NET `GroupJoin`: it yields exactly one result per outer element, in outer order. Outer elements without a match get an empty group. The result selector receives the matching inner elements as a re-enumerable `FlpList` (a snapshot, in inner order). Like .NET, `inner` is only enumerated once the outer sequence yields its first element, so an empty outer sequence never touches `inner`.
|
|
374
|
+
* `cross_join()` has no .NET LINQ equivalent. It yields the cartesian product: outer order, then inner order for each outer element. There are no keys, so only `inner` and an optional result selector are taken. If `inner` is empty the result is empty and the outer sequence is not enumerated.
|
|
375
|
+
* Argument validation is eager (`InnerNoneError`, `OuterKeySelectorNoneError`, `InnerKeySelectorNoneError`, `ResultSelectorNoneError`; `cross_join()` has no key selectors); everything else is deferred.
|
|
336
376
|
* Custom equality comparers are not supported yet (keys are compared with `==` / `hash`, like `group_by()`).
|
|
337
377
|
|
|
338
378
|
## Execution Characteristics
|
|
@@ -343,15 +383,27 @@ Lazy execution does not mean that every operator is streaming. Some operators mu
|
|
|
343
383
|
| Operator | Execution deferred | Processes incrementally | Buffers input |
|
|
344
384
|
| ---------------------- | ------------------ | ----------------------- | ------------- |
|
|
345
385
|
| `where()` / `select()` | Yes | Yes | No |
|
|
386
|
+
| `index()` | Yes | Yes | No |
|
|
387
|
+
| `skip_last()` | Yes | Yes | `count` elements (none on `FlpList`) |
|
|
388
|
+
| `take_last()` | Yes | No (`FlpList`: Yes) | `count` elements (none on `FlpList`) |
|
|
389
|
+
| `default_if_empty()` | Yes | Yes | No |
|
|
346
390
|
| `order_by()` | Yes | No | Yes |
|
|
347
391
|
| `group_by()` | Yes | No | Yes |
|
|
348
392
|
| `join()` | Yes | Yes (outer) | Yes (inner) |
|
|
349
393
|
| `left_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
350
394
|
| `full_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
395
|
+
| `group_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
396
|
+
| `cross_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
351
397
|
|
|
352
398
|
`order_by()` and `group_by()` therefore remain deferred at query construction time, but enumeration of either operator requires buffering its upstream input.
|
|
353
399
|
|
|
354
|
-
`
|
|
400
|
+
On `FlpIt`, `skip_last()` streams with a look-ahead of `count` elements: it holds back at most `count` elements and releases each one as soon as `count` newer elements have been read. `take_last()` cannot know which elements are last before the source is exhausted, so its first element is produced only after the whole source was consumed (once); it keeps at most `count` elements in memory. `FlpList` knows its length, so both operators index directly (no buffering, no read-ahead), reading the length when enumeration starts. With `count <= 0`, `skip_last()` returns every element and `take_last()` is empty without enumerating the source.
|
|
401
|
+
|
|
402
|
+
`default_if_empty(default)` streams the source unchanged and yields `default` only if the source produced no element (falsy elements such as `0` or `None` do not count as empty). The default value is mandatory: Python has no `default(T)`, so the parameterless .NET overload is not provided; pass the value explicitly (e.g. `default_if_empty(None)` for .NET's `DefaultIfEmpty()` on a reference or nullable type). On `FlpList`, emptiness is checked when enumeration starts.
|
|
403
|
+
|
|
404
|
+
`join()`, `left_join()`, `full_join()` and `group_join()` build a hash lookup of the `inner` sequence when enumeration starts and stream the outer sequence (O(N + M)); `group_join()` builds it once the outer sequence yields its first element. `cross_join()` buffers `inner` into a list once (it is traversed again for every outer element) and streams the outer sequence; the output size is N × M.
|
|
405
|
+
|
|
406
|
+
`to_lookup(key_selector[, element_selector])` is the terminal counterpart (.NET `ToLookup`): it enumerates the source once, immediately, and returns a read-only, re-enumerable `Lookup`, itself a `FlpIt` of `Grouping`s in order of first key appearance. `len(lookup)` is the number of keys, `lookup[key]` returns the key's elements or an empty sequence for a missing key, and `key in lookup` / `lookup.contains(key)` test for a key. `None` is a valid key. Keys are compared with `==` / `hash`; comparer overloads are not supported yet.
|
|
355
407
|
|
|
356
408
|
`group_by()` produces a query of groupings rather than terminating the pipeline:
|
|
357
409
|
|
|
@@ -469,24 +521,32 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
469
521
|
| │ ├── test_aggregate.py | 42 |
|
|
470
522
|
| │ ├── test_all.py | 80 |
|
|
471
523
|
| │ ├── test_any.py | 90 |
|
|
524
|
+
| │ ├── test_append_prepend.py | 36 |
|
|
472
525
|
| │ ├── test_average.py | 572 |
|
|
526
|
+
| │ ├── test_cast.py | 45 |
|
|
473
527
|
| │ ├── test_chunk.py | 22 |
|
|
474
528
|
| │ ├── test_concat.py | 64 |
|
|
475
529
|
| │ ├── test_contains.py | 108 |
|
|
476
530
|
| │ ├── test_count.py | 37 |
|
|
531
|
+
| │ ├── test_default_if_empty.py | 37 |
|
|
477
532
|
| │ ├── test_distinct.py | 87 |
|
|
478
533
|
| │ ├── test_element_at.py | 43 |
|
|
534
|
+
| │ ├── test_except.py | 68 |
|
|
479
535
|
| │ ├── test_first.py | 29 |
|
|
480
536
|
| │ ├── test_first_or_default.py | 50 |
|
|
481
537
|
| │ ├── test_full_join.py | 37 |
|
|
482
538
|
| │ ├── test_generic_list.py | 95 |
|
|
483
539
|
| │ ├── test_group_by.py | 23 |
|
|
540
|
+
| │ ├── test_group_join.py | 53 |
|
|
541
|
+
| │ ├── test_index.py | 6 |
|
|
542
|
+
| │ ├── test_intersect.py | 42 |
|
|
484
543
|
| │ ├── test_join.py | 47 |
|
|
485
544
|
| │ ├── test_last.py | 29 |
|
|
486
545
|
| │ ├── test_last_or_default.py | 45 |
|
|
487
546
|
| │ ├── test_left_join.py | 47 |
|
|
488
547
|
| │ ├── test_max.py | 1100 |
|
|
489
548
|
| │ ├── test_min.py | 968 |
|
|
549
|
+
| │ ├── test_of_type.py | 38 |
|
|
490
550
|
| │ ├── test_order_by.py | 100 |
|
|
491
551
|
| │ ├── test_order_descending_by.py | 45 |
|
|
492
552
|
| │ ├── test_reverse.py | 35 |
|
|
@@ -495,10 +555,16 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
495
555
|
| │ ├── test_single.py | 34 |
|
|
496
556
|
| │ ├── test_single_or_default.py | 48 |
|
|
497
557
|
| │ ├── test_skip.py | 75 |
|
|
558
|
+
| │ ├── test_skip_last.py | 1221 |
|
|
498
559
|
| │ ├── test_sum.py | 134 |
|
|
499
560
|
| │ ├── test_take.py | 39 |
|
|
561
|
+
| │ ├── test_take_last.py | 1221 |
|
|
500
562
|
| │ ├── test_then_by.py | 40 |
|
|
501
563
|
| │ ├── test_then_descending_by.py | 34 |
|
|
564
|
+
| │ ├── test_to_dictionary.py | 32 |
|
|
565
|
+
| │ ├── test_to_list.py | 40 |
|
|
566
|
+
| │ ├── test_to_lookup.py | 26 |
|
|
567
|
+
| │ ├── test_union.py | 62 |
|
|
502
568
|
| │ ├── test_where.py | 76 |
|
|
503
569
|
| │ └── test_zip.py | 101 |
|
|
504
570
|
| └── task/ | |
|
|
@@ -508,6 +574,6 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
508
574
|
| ├── test_task_rt.py | 12 |
|
|
509
575
|
| └── test_task_rt_core.py | 22 |
|
|
510
576
|
--------------------------------------------------------------------------------
|
|
511
|
-
| GRAND TOTALS |
|
|
577
|
+
| GRAND TOTALS | 7660 |
|
|
512
578
|
================================================================================
|
|
513
579
|
```
|
|
@@ -249,6 +249,38 @@ list(FlpList([1, 2, 2, 3])).count(2) # 2
|
|
|
249
249
|
|
|
250
250
|
This behavior is a core part of `FlpList`'s LINQ-oriented contract, not an incomplete `list` implementation.
|
|
251
251
|
|
|
252
|
+
## Indexed Elements: `index()`
|
|
253
|
+
|
|
254
|
+
`index()` is the **.NET 9 `Index()` operator**. It pairs every element with its zero-based position and yields `IndexTuple(index, item)`. `IndexTuple` is a `NamedTuple`, so it unpacks and compares like a plain `(index, item)` tuple:
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
flp.it(["a", "b", "c"]).index()
|
|
258
|
+
# [(0, "a"), (1, "b"), (2, "c")] (.NET 9 Index)
|
|
259
|
+
|
|
260
|
+
for i, name in flp.it(["a", "b"]).index():
|
|
261
|
+
...
|
|
262
|
+
|
|
263
|
+
flp.it(names).index().where(lambda t: t.index % 2 == 0).select(lambda t: t.item)
|
|
264
|
+
# every second name, starting with the first
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
* Execution is deferred and the source is streamed element by element; nothing is buffered.
|
|
268
|
+
* The .NET `OverflowException` after `int.MaxValue` elements does not apply: Python integers do not overflow.
|
|
269
|
+
|
|
270
|
+
### No indexed `select()` / `where()` overloads
|
|
271
|
+
|
|
272
|
+
.NET also offers `Select((item, index) => ...)` and `Where((item, index) => ...)`.
|
|
273
|
+
With `index()` available, these overloads are **not planned** for `select()` and `where()`.
|
|
274
|
+
This is a consequence of the Python runtime rather than an oversight: .NET picks between `x => ...` and `(x, i) => ...` at compile time through overload resolution,
|
|
275
|
+
but Python has no overloads at runtime. A method receives one callable, and the only way to tell the two shapes apart would be to inspect that callable's signature on every call.
|
|
276
|
+
That is fragile (builtins, `functools.partial`, `*args`, C-implemented callables) and would make behavior depend on how a function happens to be written.
|
|
277
|
+
Keeping a single, unambiguous signature per operator and composing with `index()` expresses the same thing explicitly:
|
|
278
|
+
|
|
279
|
+
```python
|
|
280
|
+
flp.it(source).index().select(lambda t: f"{t.index}: {t.item}") # instead of Select((x, i) => ...)
|
|
281
|
+
flp.it(source).index().where(lambda t: t.index >= 2).select(lambda t: t.item) # instead of Where((x, i) => ...)
|
|
282
|
+
```
|
|
283
|
+
|
|
252
284
|
## 🔗 Independent Query Pipelines
|
|
253
285
|
|
|
254
286
|
Query pipelines can be composed independently without mutating the queries they were derived from:
|
|
@@ -300,15 +332,23 @@ flp.it(customers).left_join(orders, lambda c: c[1], lambda o: o[1], lambda c, o:
|
|
|
300
332
|
# [("Prakash", 10), ("Prakash", 11), ("Tim", None), ("Robert", None)] (.NET 10 LeftJoin)
|
|
301
333
|
|
|
302
334
|
flp.it(customers).full_join(orders, lambda c: c[1], lambda o: o[1], lambda c, o: (c and c[0], o and o[0]))
|
|
303
|
-
# [("Prakash", 10), ("Prakash", 11), ("Tim", None), ("Robert", None), (None, 12)]
|
|
335
|
+
# [("Prakash", 10), ("Prakash", 11), ("Tim", None), ("Robert", None), (None, 12)] (.NET 11 FullJoin)
|
|
336
|
+
|
|
337
|
+
flp.it(customers).group_join(orders, lambda c: c[1], lambda o: o[1], lambda c, os: (c[0], os.select(lambda o: o[0]).to_list()))
|
|
338
|
+
# [("Prakash", [10, 11]), ("Tim", []), ("Robert", [])] group join (.NET GroupJoin)
|
|
339
|
+
|
|
340
|
+
flp.it([1, 2]).cross_join(["a", "b"], lambda n, c: f"{n}{c}")
|
|
341
|
+
# ["1a", "1b", "2a", "2b"] cross join (no .NET equivalent)
|
|
304
342
|
```
|
|
305
343
|
|
|
306
|
-
Without a result selector
|
|
344
|
+
Without a result selector `join()`, `left_join()`, `full_join()` and `cross_join()` yield `JoinTuple(outer, inner)`; `group_join()` yields a `Grouping` whose `key` is the outer element and whose items are its matching inner elements.
|
|
307
345
|
|
|
308
|
-
* Elements whose key is `None` never match. `left_join()` / `full_join()` still emit them as unmatched.
|
|
346
|
+
* Elements whose key is `None` never match. `left_join()` / `full_join()` still emit them as unmatched; `group_join()` still emits them with an empty group.
|
|
309
347
|
* An unmatched side is passed to the result selector as `None` (the Python equivalent of .NET `default`).
|
|
310
|
-
* `full_join()`
|
|
311
|
-
*
|
|
348
|
+
* `full_join()` follows .NET 11 `FullJoin` (`join()` / `left_join()` follow .NET 10 and earlier). It yields the `left_join()` rows in outer order, followed by every inner element that was never matched (in inner order).
|
|
349
|
+
* `group_join()` follows .NET `GroupJoin`: it yields exactly one result per outer element, in outer order. Outer elements without a match get an empty group. The result selector receives the matching inner elements as a re-enumerable `FlpList` (a snapshot, in inner order). Like .NET, `inner` is only enumerated once the outer sequence yields its first element, so an empty outer sequence never touches `inner`.
|
|
350
|
+
* `cross_join()` has no .NET LINQ equivalent. It yields the cartesian product: outer order, then inner order for each outer element. There are no keys, so only `inner` and an optional result selector are taken. If `inner` is empty the result is empty and the outer sequence is not enumerated.
|
|
351
|
+
* Argument validation is eager (`InnerNoneError`, `OuterKeySelectorNoneError`, `InnerKeySelectorNoneError`, `ResultSelectorNoneError`; `cross_join()` has no key selectors); everything else is deferred.
|
|
312
352
|
* Custom equality comparers are not supported yet (keys are compared with `==` / `hash`, like `group_by()`).
|
|
313
353
|
|
|
314
354
|
## Execution Characteristics
|
|
@@ -319,15 +359,27 @@ Lazy execution does not mean that every operator is streaming. Some operators mu
|
|
|
319
359
|
| Operator | Execution deferred | Processes incrementally | Buffers input |
|
|
320
360
|
| ---------------------- | ------------------ | ----------------------- | ------------- |
|
|
321
361
|
| `where()` / `select()` | Yes | Yes | No |
|
|
362
|
+
| `index()` | Yes | Yes | No |
|
|
363
|
+
| `skip_last()` | Yes | Yes | `count` elements (none on `FlpList`) |
|
|
364
|
+
| `take_last()` | Yes | No (`FlpList`: Yes) | `count` elements (none on `FlpList`) |
|
|
365
|
+
| `default_if_empty()` | Yes | Yes | No |
|
|
322
366
|
| `order_by()` | Yes | No | Yes |
|
|
323
367
|
| `group_by()` | Yes | No | Yes |
|
|
324
368
|
| `join()` | Yes | Yes (outer) | Yes (inner) |
|
|
325
369
|
| `left_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
326
370
|
| `full_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
371
|
+
| `group_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
372
|
+
| `cross_join()` | Yes | Yes (outer) | Yes (inner) |
|
|
327
373
|
|
|
328
374
|
`order_by()` and `group_by()` therefore remain deferred at query construction time, but enumeration of either operator requires buffering its upstream input.
|
|
329
375
|
|
|
330
|
-
`
|
|
376
|
+
On `FlpIt`, `skip_last()` streams with a look-ahead of `count` elements: it holds back at most `count` elements and releases each one as soon as `count` newer elements have been read. `take_last()` cannot know which elements are last before the source is exhausted, so its first element is produced only after the whole source was consumed (once); it keeps at most `count` elements in memory. `FlpList` knows its length, so both operators index directly (no buffering, no read-ahead), reading the length when enumeration starts. With `count <= 0`, `skip_last()` returns every element and `take_last()` is empty without enumerating the source.
|
|
377
|
+
|
|
378
|
+
`default_if_empty(default)` streams the source unchanged and yields `default` only if the source produced no element (falsy elements such as `0` or `None` do not count as empty). The default value is mandatory: Python has no `default(T)`, so the parameterless .NET overload is not provided; pass the value explicitly (e.g. `default_if_empty(None)` for .NET's `DefaultIfEmpty()` on a reference or nullable type). On `FlpList`, emptiness is checked when enumeration starts.
|
|
379
|
+
|
|
380
|
+
`join()`, `left_join()`, `full_join()` and `group_join()` build a hash lookup of the `inner` sequence when enumeration starts and stream the outer sequence (O(N + M)); `group_join()` builds it once the outer sequence yields its first element. `cross_join()` buffers `inner` into a list once (it is traversed again for every outer element) and streams the outer sequence; the output size is N × M.
|
|
381
|
+
|
|
382
|
+
`to_lookup(key_selector[, element_selector])` is the terminal counterpart (.NET `ToLookup`): it enumerates the source once, immediately, and returns a read-only, re-enumerable `Lookup`, itself a `FlpIt` of `Grouping`s in order of first key appearance. `len(lookup)` is the number of keys, `lookup[key]` returns the key's elements or an empty sequence for a missing key, and `key in lookup` / `lookup.contains(key)` test for a key. `None` is a valid key. Keys are compared with `==` / `hash`; comparer overloads are not supported yet.
|
|
331
383
|
|
|
332
384
|
`group_by()` produces a query of groupings rather than terminating the pipeline:
|
|
333
385
|
|
|
@@ -445,24 +497,32 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
445
497
|
| │ ├── test_aggregate.py | 42 |
|
|
446
498
|
| │ ├── test_all.py | 80 |
|
|
447
499
|
| │ ├── test_any.py | 90 |
|
|
500
|
+
| │ ├── test_append_prepend.py | 36 |
|
|
448
501
|
| │ ├── test_average.py | 572 |
|
|
502
|
+
| │ ├── test_cast.py | 45 |
|
|
449
503
|
| │ ├── test_chunk.py | 22 |
|
|
450
504
|
| │ ├── test_concat.py | 64 |
|
|
451
505
|
| │ ├── test_contains.py | 108 |
|
|
452
506
|
| │ ├── test_count.py | 37 |
|
|
507
|
+
| │ ├── test_default_if_empty.py | 37 |
|
|
453
508
|
| │ ├── test_distinct.py | 87 |
|
|
454
509
|
| │ ├── test_element_at.py | 43 |
|
|
510
|
+
| │ ├── test_except.py | 68 |
|
|
455
511
|
| │ ├── test_first.py | 29 |
|
|
456
512
|
| │ ├── test_first_or_default.py | 50 |
|
|
457
513
|
| │ ├── test_full_join.py | 37 |
|
|
458
514
|
| │ ├── test_generic_list.py | 95 |
|
|
459
515
|
| │ ├── test_group_by.py | 23 |
|
|
516
|
+
| │ ├── test_group_join.py | 53 |
|
|
517
|
+
| │ ├── test_index.py | 6 |
|
|
518
|
+
| │ ├── test_intersect.py | 42 |
|
|
460
519
|
| │ ├── test_join.py | 47 |
|
|
461
520
|
| │ ├── test_last.py | 29 |
|
|
462
521
|
| │ ├── test_last_or_default.py | 45 |
|
|
463
522
|
| │ ├── test_left_join.py | 47 |
|
|
464
523
|
| │ ├── test_max.py | 1100 |
|
|
465
524
|
| │ ├── test_min.py | 968 |
|
|
525
|
+
| │ ├── test_of_type.py | 38 |
|
|
466
526
|
| │ ├── test_order_by.py | 100 |
|
|
467
527
|
| │ ├── test_order_descending_by.py | 45 |
|
|
468
528
|
| │ ├── test_reverse.py | 35 |
|
|
@@ -471,10 +531,16 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
471
531
|
| │ ├── test_single.py | 34 |
|
|
472
532
|
| │ ├── test_single_or_default.py | 48 |
|
|
473
533
|
| │ ├── test_skip.py | 75 |
|
|
534
|
+
| │ ├── test_skip_last.py | 1221 |
|
|
474
535
|
| │ ├── test_sum.py | 134 |
|
|
475
536
|
| │ ├── test_take.py | 39 |
|
|
537
|
+
| │ ├── test_take_last.py | 1221 |
|
|
476
538
|
| │ ├── test_then_by.py | 40 |
|
|
477
539
|
| │ ├── test_then_descending_by.py | 34 |
|
|
540
|
+
| │ ├── test_to_dictionary.py | 32 |
|
|
541
|
+
| │ ├── test_to_list.py | 40 |
|
|
542
|
+
| │ ├── test_to_lookup.py | 26 |
|
|
543
|
+
| │ ├── test_union.py | 62 |
|
|
478
544
|
| │ ├── test_where.py | 76 |
|
|
479
545
|
| │ └── test_zip.py | 101 |
|
|
480
546
|
| └── task/ | |
|
|
@@ -484,6 +550,6 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
484
550
|
| ├── test_task_rt.py | 12 |
|
|
485
551
|
| └── test_task_rt_core.py | 22 |
|
|
486
552
|
--------------------------------------------------------------------------------
|
|
487
|
-
| GRAND TOTALS |
|
|
553
|
+
| GRAND TOTALS | 7660 |
|
|
488
554
|
================================================================================
|
|
489
555
|
```
|
|
@@ -7,6 +7,7 @@ __version__ = version("flpit")
|
|
|
7
7
|
# noinspection protected-member
|
|
8
8
|
from flpit.core._zip import ZipTuple
|
|
9
9
|
from flpit.core._join import JoinTuple
|
|
10
|
+
from flpit.core._index import IndexTuple
|
|
10
11
|
|
|
11
12
|
from flpit import flp
|
|
12
13
|
from flpit.core.linq import (
|
|
@@ -33,6 +34,7 @@ from flpit.core.linq import (
|
|
|
33
34
|
PredicateNoneError,
|
|
34
35
|
CollectionNoneError,
|
|
35
36
|
SelectorNoneError,
|
|
37
|
+
ElementSelectorNoneError,
|
|
36
38
|
SecondNoneError,
|
|
37
39
|
FuncNoneError,
|
|
38
40
|
ResultSelectorNoneError,
|
|
@@ -45,12 +47,14 @@ from flpit.core.linq import (
|
|
|
45
47
|
)
|
|
46
48
|
|
|
47
49
|
from flpit.core._grouping import Grouping
|
|
50
|
+
from flpit.core._lookup import Lookup
|
|
48
51
|
|
|
49
52
|
__all__ = [
|
|
50
53
|
"flp",
|
|
51
54
|
"FlpIt",
|
|
52
55
|
"FlpList",
|
|
53
56
|
"Grouping",
|
|
57
|
+
"Lookup",
|
|
54
58
|
"OrderedIt",
|
|
55
59
|
|
|
56
60
|
"InvalidOperationError",
|
|
@@ -65,6 +69,7 @@ __all__ = [
|
|
|
65
69
|
"PredicateNoneError",
|
|
66
70
|
"CollectionNoneError",
|
|
67
71
|
"SelectorNoneError",
|
|
72
|
+
"ElementSelectorNoneError",
|
|
68
73
|
"SecondNoneError",
|
|
69
74
|
"FuncNoneError",
|
|
70
75
|
"ResultSelectorNoneError",
|
|
@@ -77,5 +82,6 @@ __all__ = [
|
|
|
77
82
|
|
|
78
83
|
"ZipTuple",
|
|
79
84
|
"JoinTuple",
|
|
85
|
+
"IndexTuple",
|
|
80
86
|
]
|
|
81
87
|
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from typing import NamedTuple
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class IndexTuple[TItem](NamedTuple):
|
|
5
|
+
"""
|
|
6
|
+
Result of ``index()``: the zero-based position of an element together with the element itself.
|
|
7
|
+
|
|
8
|
+
Mirrors the .NET ``(int Index, TSource Item)`` tuple.
|
|
9
|
+
The `index` field hides the tuple.index(...) function.
|
|
10
|
+
It doesn't serve a practical purpose in this scenario anyway
|
|
11
|
+
"""
|
|
12
|
+
index: int
|
|
13
|
+
item: TItem
|
|
@@ -2,6 +2,6 @@ from typing import NamedTuple
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
class JoinTuple[TOuter, TInner](NamedTuple):
|
|
5
|
-
"""Default result of join / left_join / full_join when no result selector is given."""
|
|
5
|
+
"""Default result of join / left_join / full_join / cross_join when no result selector is given."""
|
|
6
6
|
outer: TOuter
|
|
7
7
|
inner: TInner
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from typing import override
|
|
2
|
+
|
|
3
|
+
from flpit.core.linq import FlpIt, FlpList
|
|
4
|
+
from flpit.core._grouping import Grouping
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Lookup[TKey, TElement](FlpIt[Grouping[TKey, TElement]]):
|
|
8
|
+
"""
|
|
9
|
+
Read-only, materialized one-to-many map of keys to groupings (.NET ``ILookup<TKey, TElement>``).
|
|
10
|
+
|
|
11
|
+
Enumerates its groupings in the order their keys first appeared in the source and can be enumerated
|
|
12
|
+
repeatedly. ``None`` is a valid key. Indexing a missing key yields an empty sequence instead of raising.
|
|
13
|
+
"""
|
|
14
|
+
__slots__ = ("_groups",)
|
|
15
|
+
|
|
16
|
+
def __init__(self, groups: dict[TKey, Grouping[TKey, TElement]]) -> None:
|
|
17
|
+
self._groups: dict[TKey, Grouping[TKey, TElement]] = groups
|
|
18
|
+
super().__init__(groups.values())
|
|
19
|
+
|
|
20
|
+
def __len__(self) -> int:
|
|
21
|
+
"""Number of key/grouping pairs (.NET ``ILookup.Count``)."""
|
|
22
|
+
return len(self._groups)
|
|
23
|
+
|
|
24
|
+
def __getitem__(self, key: TKey) -> FlpList[TElement]:
|
|
25
|
+
"""Elements of ``key``, or an empty sequence if the key is missing (.NET ``ILookup[key]``)."""
|
|
26
|
+
grouping = self._groups.get(key)
|
|
27
|
+
return FlpList[TElement]() if grouping is None else grouping
|
|
28
|
+
|
|
29
|
+
def __contains__(self, key: object) -> bool:
|
|
30
|
+
"""``key in lookup`` tests for a key (.NET ``ILookup.Contains(key)``)."""
|
|
31
|
+
return key in self._groups
|
|
32
|
+
|
|
33
|
+
@override
|
|
34
|
+
def contains(self, key: TKey) -> bool: # type: ignore[override]
|
|
35
|
+
"""Determines whether ``key`` is in the lookup (.NET ``ILookup.Contains(key)``, hides LINQ ``Contains``)."""
|
|
36
|
+
return key in self._groups
|
|
37
|
+
|
|
38
|
+
@override
|
|
39
|
+
def __repr__(self) -> str:
|
|
40
|
+
return f"Lookup({list(self._groups.values())!r})"
|
|
@@ -7,7 +7,8 @@ from decimal import Decimal, Overflow, Inexact
|
|
|
7
7
|
from contextlib import AbstractContextManager
|
|
8
8
|
|
|
9
9
|
import builtins
|
|
10
|
-
|
|
10
|
+
import sys
|
|
11
|
+
from collections import UserList, deque
|
|
11
12
|
from functools import wraps, partial as _partial
|
|
12
13
|
from operator import is_not as _is_not, ne as _ne, eq as _eq
|
|
13
14
|
from itertools import islice, chain, compress
|
|
@@ -37,6 +38,7 @@ from typing import (
|
|
|
37
38
|
from flpit.json import JsonConvert, JsonSerializerOptions
|
|
38
39
|
from flpit import ZipTuple
|
|
39
40
|
from flpit.core._join import JoinTuple
|
|
41
|
+
from flpit.core._index import IndexTuple
|
|
40
42
|
|
|
41
43
|
TKey = TypeVar("TKey")
|
|
42
44
|
TOther = TypeVar("TOther")
|
|
@@ -100,6 +102,10 @@ class SelectorNoneError(ArgumentNullError):
|
|
|
100
102
|
def __init__(self):
|
|
101
103
|
super().__init__("keySelector")
|
|
102
104
|
|
|
105
|
+
class ElementSelectorNoneError(ArgumentNullError):
|
|
106
|
+
def __init__(self) -> None:
|
|
107
|
+
super().__init__("elementSelector")
|
|
108
|
+
|
|
103
109
|
class SecondNoneError(ArgumentNullError):
|
|
104
110
|
def __init__(self):
|
|
105
111
|
super().__init__("second")
|
|
@@ -351,7 +357,7 @@ def _validate_join_args(
|
|
|
351
357
|
inner_key_selector: Any,
|
|
352
358
|
result_selector: Any,
|
|
353
359
|
) -> None:
|
|
354
|
-
"""Eager argument validation shared by join / left_join / full_join (mirrors .NET)."""
|
|
360
|
+
"""Eager argument validation shared by join / left_join / full_join / group_join (mirrors .NET)."""
|
|
355
361
|
if inner is None:
|
|
356
362
|
raise InnerNoneError()
|
|
357
363
|
if outer_key_selector is None:
|
|
@@ -496,6 +502,20 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
496
502
|
raise SelectorNoneError()
|
|
497
503
|
return FlpIt(_SelectIterable(self._node_source(), selector))
|
|
498
504
|
|
|
505
|
+
def index(self) -> FlpIt[IndexTuple[TItem]]:
|
|
506
|
+
"""
|
|
507
|
+
Returns an enumerable that incorporates the element's index into a tuple (.NET 9 ``Index()``).
|
|
508
|
+
|
|
509
|
+
Yields ``IndexTuple(index, item)`` for every element, with ``index`` starting at 0. Execution is
|
|
510
|
+
deferred and the source is streamed element by element; being a plain ``tuple`` subclass the
|
|
511
|
+
result unpacks as ``for i, item in query.index()``.
|
|
512
|
+
"""
|
|
513
|
+
def _generator() -> Iterator[IndexTuple[TItem]]:
|
|
514
|
+
for position, item in enumerate(self):
|
|
515
|
+
yield IndexTuple(position, item)
|
|
516
|
+
|
|
517
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
518
|
+
|
|
499
519
|
def select_many[TResult](
|
|
500
520
|
self, selector: Callable[[TItem], Iterable[TResult]]
|
|
501
521
|
) -> FlpIt[TResult]:
|
|
@@ -544,15 +564,80 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
544
564
|
|
|
545
565
|
return FlpIt(_FactoryIterable(_generator))
|
|
546
566
|
|
|
567
|
+
def skip_last(self, count: int) -> "FlpIt[TItem]":
|
|
568
|
+
"""
|
|
569
|
+
Returns the elements of the sequence with the last ``count`` elements omitted (.NET ``SkipLast()``).
|
|
570
|
+
|
|
571
|
+
Execution is deferred and the source is streamed: at most ``count`` elements are read ahead of
|
|
572
|
+
the element currently being yielded, so the operator buffers no more than ``count`` elements.
|
|
573
|
+
A ``count`` of zero or less omits nothing and returns the sequence unchanged.
|
|
574
|
+
"""
|
|
575
|
+
if count <= 0:
|
|
576
|
+
return self
|
|
577
|
+
|
|
578
|
+
def _generator() -> Iterator[TItem]:
|
|
579
|
+
queue: deque[TItem] = deque()
|
|
580
|
+
for item in self:
|
|
581
|
+
if len(queue) == count:
|
|
582
|
+
yield queue.popleft()
|
|
583
|
+
queue.append(item)
|
|
584
|
+
|
|
585
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
586
|
+
|
|
587
|
+
def take_last(self, count: int) -> "FlpIt[TItem]":
|
|
588
|
+
"""
|
|
589
|
+
Returns the last ``count`` elements of the sequence (.NET ``TakeLast()``).
|
|
590
|
+
|
|
591
|
+
Execution is deferred until the returned sequence is enumerated. The last elements are only known
|
|
592
|
+
once the end of the source is reached, so enumeration first consumes the whole source (keeping
|
|
593
|
+
at most ``count`` elements in memory) and then yields the retained elements in source order.
|
|
594
|
+
A ``count`` of zero or less yields an empty sequence without touching the source.
|
|
595
|
+
"""
|
|
596
|
+
if count <= 0:
|
|
597
|
+
return FlpIt(())
|
|
598
|
+
|
|
599
|
+
def _generator() -> Iterator[TItem]:
|
|
600
|
+
# deque() cannot hold a maxlen above sys.maxsize; such a count keeps everything anyway.
|
|
601
|
+
yield from deque(self, maxlen=min(count, sys.maxsize))
|
|
602
|
+
|
|
603
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
604
|
+
|
|
605
|
+
def default_if_empty[TResult](self, default: TResult) -> FlpIt[TItem | TResult]:
|
|
606
|
+
"""
|
|
607
|
+
Returns the elements of the sequence, or a sequence containing only ``default`` if the
|
|
608
|
+
sequence is empty (.NET ``DefaultIfEmpty(defaultValue)``).
|
|
609
|
+
|
|
610
|
+
Execution is deferred and the source is streamed; it is enumerated once per enumeration of
|
|
611
|
+
the result. ``default`` is mandatory: Python has no ``default(T)``, so the parameterless
|
|
612
|
+
.NET overload is not provided.
|
|
613
|
+
"""
|
|
614
|
+
def _generator() -> Iterator[TItem | TResult]:
|
|
615
|
+
iterator = iter(self)
|
|
616
|
+
for item in iterator:
|
|
617
|
+
yield item
|
|
618
|
+
yield from iterator
|
|
619
|
+
return
|
|
620
|
+
yield default
|
|
621
|
+
|
|
622
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
623
|
+
|
|
547
624
|
def cast[TResult](self, target_type: Type[TResult]) -> FlpIt[TResult]:
|
|
548
625
|
"""Casts elements to a specified type or raises TypeError if cast fails."""
|
|
626
|
+
_VALUE_TYPES = (int, float, bool, complex)
|
|
627
|
+
|
|
549
628
|
def _generator() -> Iterator[TResult]:
|
|
550
629
|
for item in self:
|
|
630
|
+
if item is None:
|
|
631
|
+
if target_type in _VALUE_TYPES:
|
|
632
|
+
raise AttributeError("Cannot unbox None to a non-nullable value type")
|
|
633
|
+
yield item
|
|
634
|
+
continue
|
|
635
|
+
|
|
551
636
|
if not isinstance(item, target_type):
|
|
552
637
|
raise TypeError(
|
|
553
638
|
f"Cannot cast element {item!r} of type {type(item).__name__} to {target_type.__name__}"
|
|
554
639
|
)
|
|
555
|
-
yield item
|
|
640
|
+
yield item
|
|
556
641
|
|
|
557
642
|
return FlpIt(_FactoryIterable(_generator))
|
|
558
643
|
|
|
@@ -560,7 +645,7 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
560
645
|
"""Filters the elements of an Iterable based on a specified type."""
|
|
561
646
|
def _generator() -> Iterator[TResult]:
|
|
562
647
|
for item in self:
|
|
563
|
-
if isinstance(item, target_type):
|
|
648
|
+
if item is not None and isinstance(item, target_type):
|
|
564
649
|
yield item # type: ignore[misc]
|
|
565
650
|
|
|
566
651
|
return FlpIt(_FactoryIterable(_generator))
|
|
@@ -593,6 +678,94 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
593
678
|
|
|
594
679
|
return FlpIt(_FactoryIterable(_generator))
|
|
595
680
|
|
|
681
|
+
def except_(self, second: Iterable[TItem]) -> FlpIt[TItem]:
|
|
682
|
+
"""Produces the set difference of two sequences (deferred).
|
|
683
|
+
|
|
684
|
+
Named ``except_`` because ``except`` is a reserved word in Python.
|
|
685
|
+
Returns the distinct elements of this sequence that do not appear in
|
|
686
|
+
``second``, in source order. ``second`` is fully enumerated on first iteration.
|
|
687
|
+
"""
|
|
688
|
+
if second is None:
|
|
689
|
+
raise SecondNoneError()
|
|
690
|
+
|
|
691
|
+
def _generator() -> Iterator[TItem]:
|
|
692
|
+
seen: Set[TItem] = set(second)
|
|
693
|
+
for item in self:
|
|
694
|
+
if item not in seen:
|
|
695
|
+
seen.add(item)
|
|
696
|
+
yield item
|
|
697
|
+
|
|
698
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
699
|
+
|
|
700
|
+
def except_by(
|
|
701
|
+
self,
|
|
702
|
+
second: Iterable[TKey],
|
|
703
|
+
key_selector: Callable[[TItem], TKey],
|
|
704
|
+
) -> FlpIt[TItem]:
|
|
705
|
+
"""Produces the set difference of two sequences according to a key selector (deferred).
|
|
706
|
+
|
|
707
|
+
Returns the elements of this sequence, distinct by key, whose key does not
|
|
708
|
+
appear in ``second``, in source order.
|
|
709
|
+
"""
|
|
710
|
+
if second is None:
|
|
711
|
+
raise SecondNoneError()
|
|
712
|
+
if key_selector is None:
|
|
713
|
+
raise SelectorNoneError()
|
|
714
|
+
|
|
715
|
+
def _generator() -> Iterator[TItem]:
|
|
716
|
+
seen: Set[TKey] = set(second)
|
|
717
|
+
for item in self:
|
|
718
|
+
key = key_selector(item)
|
|
719
|
+
if key not in seen:
|
|
720
|
+
seen.add(key)
|
|
721
|
+
yield item
|
|
722
|
+
|
|
723
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
724
|
+
|
|
725
|
+
def intersect(self, second: Iterable[TItem]) -> FlpIt[TItem]:
|
|
726
|
+
"""Produces the set intersection of two sequences (deferred).
|
|
727
|
+
|
|
728
|
+
Returns the distinct elements of this sequence that also appear in
|
|
729
|
+
``second``, in source order. ``second`` is fully enumerated on first
|
|
730
|
+
iteration, before the first element of this sequence is requested;
|
|
731
|
+
this sequence is then streamed.
|
|
732
|
+
"""
|
|
733
|
+
if second is None:
|
|
734
|
+
raise SecondNoneError()
|
|
735
|
+
|
|
736
|
+
def _generator() -> Iterator[TItem]:
|
|
737
|
+
remaining: Set[TItem] = set(second)
|
|
738
|
+
for item in self:
|
|
739
|
+
if item in remaining:
|
|
740
|
+
remaining.remove(item)
|
|
741
|
+
yield item
|
|
742
|
+
|
|
743
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
744
|
+
|
|
745
|
+
def union(self, second: Iterable[TItem]) -> FlpIt[TItem]:
|
|
746
|
+
"""Produces the set union of two sequences (deferred).
|
|
747
|
+
|
|
748
|
+
Returns the distinct elements of this sequence followed by the distinct
|
|
749
|
+
elements of ``second`` that were not already produced, in encounter order.
|
|
750
|
+
Both sequences are streamed; ``second`` is not enumerated until this
|
|
751
|
+
sequence is exhausted.
|
|
752
|
+
"""
|
|
753
|
+
if second is None:
|
|
754
|
+
raise SecondNoneError()
|
|
755
|
+
|
|
756
|
+
def _generator() -> Iterator[TItem]:
|
|
757
|
+
seen: Set[TItem] = set()
|
|
758
|
+
for item in self:
|
|
759
|
+
if item not in seen:
|
|
760
|
+
seen.add(item)
|
|
761
|
+
yield item
|
|
762
|
+
for item in second:
|
|
763
|
+
if item not in seen:
|
|
764
|
+
seen.add(item)
|
|
765
|
+
yield item
|
|
766
|
+
|
|
767
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
768
|
+
|
|
596
769
|
@overload
|
|
597
770
|
def zip(self, second: Iterable[TOther]) -> FlpIt[ZipTuple[TItem, TOther]]: ...
|
|
598
771
|
|
|
@@ -752,7 +925,7 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
752
925
|
result_selector: Callable[[TItem | None, TInner | None], Any] | _Sentinel = _SENTINEL,
|
|
753
926
|
) -> FlpIt[Any]:
|
|
754
927
|
"""
|
|
755
|
-
Full outer join (
|
|
928
|
+
Full outer join (.NET 11 ``FullJoin``).
|
|
756
929
|
|
|
757
930
|
Produces everything ``left_join`` does (unmatched outer elements paired with ``None``),
|
|
758
931
|
followed by every inner element that was never matched by any outer element, paired with
|
|
@@ -797,6 +970,105 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
797
970
|
|
|
798
971
|
return FlpIt(_FactoryIterable(_generator))
|
|
799
972
|
|
|
973
|
+
@overload
|
|
974
|
+
def cross_join[TInner](
|
|
975
|
+
self,
|
|
976
|
+
inner: Iterable[TInner],
|
|
977
|
+
) -> FlpIt[JoinTuple[TItem, TInner]]: ...
|
|
978
|
+
|
|
979
|
+
@overload
|
|
980
|
+
def cross_join[TResult, TInner](
|
|
981
|
+
self,
|
|
982
|
+
inner: Iterable[TInner],
|
|
983
|
+
result_selector: Callable[[TItem, TInner], TResult],
|
|
984
|
+
) -> FlpIt[TResult]: ...
|
|
985
|
+
|
|
986
|
+
def cross_join[TInner](
|
|
987
|
+
self,
|
|
988
|
+
inner: Iterable[TInner],
|
|
989
|
+
result_selector: Callable[[TItem, TInner], Any] | _Sentinel = _SENTINEL,
|
|
990
|
+
) -> FlpIt[Any]:
|
|
991
|
+
"""
|
|
992
|
+
Cross join (cartesian product; no .NET LINQ equivalent).
|
|
993
|
+
|
|
994
|
+
Produces one result per (outer, inner) pair, in outer order and, per outer element,
|
|
995
|
+
in inner order. Without a result selector ``JoinTuple(outer, inner)`` is yielded.
|
|
996
|
+
Arguments are validated eagerly. The outer sequence is streamed; ``inner`` is buffered
|
|
997
|
+
once when enumeration starts, because it is traversed again for every outer element.
|
|
998
|
+
If ``inner`` is empty the result is empty and the outer sequence is not enumerated.
|
|
999
|
+
"""
|
|
1000
|
+
if inner is None:
|
|
1001
|
+
raise InnerNoneError()
|
|
1002
|
+
if result_selector is None:
|
|
1003
|
+
raise ResultSelectorNoneError()
|
|
1004
|
+
|
|
1005
|
+
def _generator() -> Iterator[Any]:
|
|
1006
|
+
inner_items = list(inner)
|
|
1007
|
+
if not inner_items:
|
|
1008
|
+
return
|
|
1009
|
+
for outer_item in self:
|
|
1010
|
+
for inner_item in inner_items:
|
|
1011
|
+
if result_selector is _SENTINEL:
|
|
1012
|
+
yield JoinTuple(outer_item, inner_item)
|
|
1013
|
+
else:
|
|
1014
|
+
yield result_selector(outer_item, inner_item)
|
|
1015
|
+
|
|
1016
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
1017
|
+
|
|
1018
|
+
@overload
|
|
1019
|
+
def group_join[TInner](
|
|
1020
|
+
self,
|
|
1021
|
+
inner: Iterable[TInner],
|
|
1022
|
+
outer_key_selector: Callable[[TItem], Any],
|
|
1023
|
+
inner_key_selector: Callable[[TInner], Any],
|
|
1024
|
+
) -> FlpIt[Grouping[TItem, TInner]]: ...
|
|
1025
|
+
|
|
1026
|
+
@overload
|
|
1027
|
+
def group_join[TResult, TInner](
|
|
1028
|
+
self,
|
|
1029
|
+
inner: Iterable[TInner],
|
|
1030
|
+
outer_key_selector: Callable[[TItem], Any],
|
|
1031
|
+
inner_key_selector: Callable[[TInner], Any],
|
|
1032
|
+
result_selector: Callable[[TItem, FlpList[TInner]], TResult],
|
|
1033
|
+
) -> FlpIt[TResult]: ...
|
|
1034
|
+
|
|
1035
|
+
def group_join[TInner](
|
|
1036
|
+
self,
|
|
1037
|
+
inner: Iterable[TInner],
|
|
1038
|
+
outer_key_selector: Callable[[TItem], Any],
|
|
1039
|
+
inner_key_selector: Callable[[TInner], Any],
|
|
1040
|
+
result_selector: Callable[[TItem, FlpList[TInner]], Any] | _Sentinel = _SENTINEL,
|
|
1041
|
+
) -> FlpIt[Any]:
|
|
1042
|
+
"""
|
|
1043
|
+
Group join (.NET ``GroupJoin``): correlates each outer element with the group of its matching inner elements.
|
|
1044
|
+
|
|
1045
|
+
Yields exactly one result per outer element, in outer order, so an outer element without a match
|
|
1046
|
+
still appears, paired with an empty group. The group holds the matching inner elements in inner order
|
|
1047
|
+
and can be enumerated repeatedly. Without a result selector a ``Grouping`` is yielded, whose ``key`` is
|
|
1048
|
+
the outer element and whose items are its matching inner elements; with one,
|
|
1049
|
+
``result_selector(outer, group)`` is yielded with ``group`` being a ``FlpList`` of the matches.
|
|
1050
|
+
Elements whose key is ``None`` never match (an outer element with a ``None`` key gets an empty group).
|
|
1051
|
+
|
|
1052
|
+
Arguments are validated eagerly. The outer sequence is streamed; like .NET, ``inner`` is buffered
|
|
1053
|
+
into a hash lookup (O(N + M)) only once the outer sequence yields its first element, so an empty outer
|
|
1054
|
+
sequence never enumerates ``inner``.
|
|
1055
|
+
"""
|
|
1056
|
+
_validate_join_args(inner, outer_key_selector, inner_key_selector, result_selector)
|
|
1057
|
+
|
|
1058
|
+
def _generator() -> Iterator[Any]:
|
|
1059
|
+
lookup: dict[Any, list[TInner]] | None = None
|
|
1060
|
+
for outer_item in self:
|
|
1061
|
+
if lookup is None:
|
|
1062
|
+
lookup = _build_lookup(inner, inner_key_selector)
|
|
1063
|
+
key = outer_key_selector(outer_item)
|
|
1064
|
+
matches = () if key is None else lookup.get(key, ())
|
|
1065
|
+
if result_selector is _SENTINEL:
|
|
1066
|
+
yield Grouping(outer_item, matches)
|
|
1067
|
+
else:
|
|
1068
|
+
yield result_selector(outer_item, FlpList(matches))
|
|
1069
|
+
|
|
1070
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
1071
|
+
|
|
800
1072
|
def chunk(self, size: int) -> FlpIt[FlpList[TItem]]:
|
|
801
1073
|
"""Splits the elements of a sequence into chunks of size at most size."""
|
|
802
1074
|
if size <= 0:
|
|
@@ -1149,13 +1421,59 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
1149
1421
|
result: dict[Any, Any] = {}
|
|
1150
1422
|
for item in self:
|
|
1151
1423
|
key = key_selector(item)
|
|
1424
|
+
|
|
1425
|
+
if key is None:
|
|
1426
|
+
raise ArgumentNullError("Value cannot be null. (Parameter 'key')")
|
|
1427
|
+
|
|
1152
1428
|
if key in result:
|
|
1153
|
-
raise
|
|
1429
|
+
raise ArgumentError(
|
|
1430
|
+
f"An item with the same key has already been added. Key: {key!r}"
|
|
1431
|
+
)
|
|
1432
|
+
|
|
1154
1433
|
value = item if element_selector is _SENTINEL else element_selector(item)
|
|
1155
1434
|
result[key] = value
|
|
1156
1435
|
|
|
1157
1436
|
return result
|
|
1158
1437
|
|
|
1438
|
+
@overload
|
|
1439
|
+
def to_lookup[TKey](
|
|
1440
|
+
self, key_selector: Callable[[TItem], TKey], /
|
|
1441
|
+
) -> Lookup[TKey, TItem]: ...
|
|
1442
|
+
|
|
1443
|
+
@overload
|
|
1444
|
+
def to_lookup[TKey, TElement](
|
|
1445
|
+
self,
|
|
1446
|
+
key_selector: Callable[[TItem], TKey],
|
|
1447
|
+
element_selector: Callable[[TItem], TElement],
|
|
1448
|
+
/,
|
|
1449
|
+
) -> Lookup[TKey, TElement]: ...
|
|
1450
|
+
|
|
1451
|
+
def to_lookup(
|
|
1452
|
+
self,
|
|
1453
|
+
key_selector: Callable[[TItem], Any],
|
|
1454
|
+
element_selector: Callable[[TItem], Any] | _Sentinel = _SENTINEL,
|
|
1455
|
+
) -> Lookup[Any, Any]:
|
|
1456
|
+
"""
|
|
1457
|
+
Materializes the sequence as a ``Lookup`` (.NET ``ToLookup``): a read-only one-to-many map of keys
|
|
1458
|
+
to groupings, in order of first key appearance. ``None`` is a valid key; missing keys index to an
|
|
1459
|
+
empty sequence. Keys are compared with ``==`` / ``hash``; comparer overloads are not provided yet.
|
|
1460
|
+
"""
|
|
1461
|
+
if key_selector is None:
|
|
1462
|
+
raise SelectorNoneError()
|
|
1463
|
+
if element_selector is None:
|
|
1464
|
+
raise ElementSelectorNoneError()
|
|
1465
|
+
|
|
1466
|
+
groups: dict[Any, list[Any]] = {}
|
|
1467
|
+
if element_selector is _SENTINEL:
|
|
1468
|
+
for item in self:
|
|
1469
|
+
groups.setdefault(key_selector(item), []).append(item)
|
|
1470
|
+
else:
|
|
1471
|
+
for item in self:
|
|
1472
|
+
key = key_selector(item)
|
|
1473
|
+
groups.setdefault(key, []).append(element_selector(item))
|
|
1474
|
+
|
|
1475
|
+
return Lookup({k: Grouping(k, v) for k, v in groups.items()})
|
|
1476
|
+
|
|
1159
1477
|
def to_list(self) -> FlpList[TItem]:
|
|
1160
1478
|
"""Explicitly materializes the query into a FlpList."""
|
|
1161
1479
|
return FlpList[TItem](self)
|
|
@@ -1549,6 +1867,9 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1549
1867
|
def select[TResult](self, selector: Callable[[TItem], TResult]) -> FlpIt[TResult]:
|
|
1550
1868
|
return FlpIt(self.__list.data).select(selector)
|
|
1551
1869
|
|
|
1870
|
+
def index(self) -> FlpIt[IndexTuple[TItem]]:
|
|
1871
|
+
return FlpIt(self.__list.data).index()
|
|
1872
|
+
|
|
1552
1873
|
def select_many[TResult](
|
|
1553
1874
|
self, selector: Callable[[TItem], Iterable[TResult]]
|
|
1554
1875
|
) -> FlpIt[TResult]:
|
|
@@ -1560,6 +1881,43 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1560
1881
|
def take(self, count: int) -> FlpIt[TItem]:
|
|
1561
1882
|
return FlpIt(self.__list.data).take(count)
|
|
1562
1883
|
|
|
1884
|
+
def skip_last(self, count: int) -> FlpIt[TItem]:
|
|
1885
|
+
data = self.__list.data
|
|
1886
|
+
|
|
1887
|
+
if count <= 0:
|
|
1888
|
+
return FlpIt(data)
|
|
1889
|
+
|
|
1890
|
+
def _generator() -> Iterator[TItem]:
|
|
1891
|
+
end = max(0, len(data) - max(0, count))
|
|
1892
|
+
yield from islice(data, end)
|
|
1893
|
+
|
|
1894
|
+
return FlpIt(
|
|
1895
|
+
_FactoryIterable(_generator)
|
|
1896
|
+
)
|
|
1897
|
+
|
|
1898
|
+
def take_last(self, count: int) -> FlpIt[TItem]:
|
|
1899
|
+
data = self.__list.data
|
|
1900
|
+
|
|
1901
|
+
if count <= 0:
|
|
1902
|
+
return FlpIt(())
|
|
1903
|
+
|
|
1904
|
+
def _generator() -> Iterator[TItem]:
|
|
1905
|
+
yield from islice(data, max(0, len(data) - count), None)
|
|
1906
|
+
|
|
1907
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
1908
|
+
|
|
1909
|
+
def default_if_empty[TResult](self, default: TResult) -> FlpIt[TItem | TResult]:
|
|
1910
|
+
data = self.__list.data
|
|
1911
|
+
|
|
1912
|
+
def _generator() -> Iterator[TItem | TResult]:
|
|
1913
|
+
# Emptiness is checked when enumeration starts, so later mutations of the list are observed.
|
|
1914
|
+
if data:
|
|
1915
|
+
yield from data
|
|
1916
|
+
else:
|
|
1917
|
+
yield default
|
|
1918
|
+
|
|
1919
|
+
return FlpIt(_FactoryIterable(_generator))
|
|
1920
|
+
|
|
1563
1921
|
def cast[TResult](self, target_type: Type[TResult]) -> FlpIt[TResult]:
|
|
1564
1922
|
return FlpIt(self.__list.data).cast(target_type)
|
|
1565
1923
|
|
|
@@ -1574,6 +1932,22 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1574
1932
|
) -> FlpIt[TItem]:
|
|
1575
1933
|
return FlpIt(self.__list.data).distinct_by(key_selector)
|
|
1576
1934
|
|
|
1935
|
+
def except_(self, second: Iterable[TItem]) -> FlpIt[TItem]:
|
|
1936
|
+
return FlpIt(self.__list.data).except_(second)
|
|
1937
|
+
|
|
1938
|
+
def except_by(
|
|
1939
|
+
self,
|
|
1940
|
+
second: Iterable[TKey],
|
|
1941
|
+
key_selector: Callable[[TItem], TKey],
|
|
1942
|
+
) -> FlpIt[TItem]:
|
|
1943
|
+
return FlpIt(self.__list.data).except_by(second, key_selector)
|
|
1944
|
+
|
|
1945
|
+
def intersect(self, second: Iterable[TItem]) -> FlpIt[TItem]:
|
|
1946
|
+
return FlpIt(self.__list.data).intersect(second)
|
|
1947
|
+
|
|
1948
|
+
def union(self, second: Iterable[TItem]) -> FlpIt[TItem]:
|
|
1949
|
+
return FlpIt(self.__list.data).union(second)
|
|
1950
|
+
|
|
1577
1951
|
@overload
|
|
1578
1952
|
def zip(self, second: Iterable[TOther]) -> FlpIt[ZipTuple[TItem, TOther]]: ...
|
|
1579
1953
|
|
|
@@ -1669,6 +2043,52 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1669
2043
|
) -> FlpIt[Any]:
|
|
1670
2044
|
return FlpIt(self.__list.data).full_join(inner, outer_key_selector, inner_key_selector, result_selector)
|
|
1671
2045
|
|
|
2046
|
+
@overload
|
|
2047
|
+
def cross_join[TInner](
|
|
2048
|
+
self,
|
|
2049
|
+
inner: Iterable[TInner],
|
|
2050
|
+
) -> FlpIt[JoinTuple[TItem, TInner]]: ...
|
|
2051
|
+
|
|
2052
|
+
@overload
|
|
2053
|
+
def cross_join[TResult, TInner](
|
|
2054
|
+
self,
|
|
2055
|
+
inner: Iterable[TInner],
|
|
2056
|
+
result_selector: Callable[[TItem, TInner], TResult],
|
|
2057
|
+
) -> FlpIt[TResult]: ...
|
|
2058
|
+
|
|
2059
|
+
def cross_join[TInner](
|
|
2060
|
+
self,
|
|
2061
|
+
inner: Iterable[TInner],
|
|
2062
|
+
result_selector: Callable[[TItem, TInner], Any] | _Sentinel = _SENTINEL,
|
|
2063
|
+
) -> FlpIt[Any]:
|
|
2064
|
+
return FlpIt(self.__list.data).cross_join(inner, result_selector)
|
|
2065
|
+
|
|
2066
|
+
@overload
|
|
2067
|
+
def group_join[TInner](
|
|
2068
|
+
self,
|
|
2069
|
+
inner: Iterable[TInner],
|
|
2070
|
+
outer_key_selector: Callable[[TItem], Any],
|
|
2071
|
+
inner_key_selector: Callable[[TInner], Any],
|
|
2072
|
+
) -> FlpIt[Grouping[TItem, TInner]]: ...
|
|
2073
|
+
|
|
2074
|
+
@overload
|
|
2075
|
+
def group_join[TResult, TInner](
|
|
2076
|
+
self,
|
|
2077
|
+
inner: Iterable[TInner],
|
|
2078
|
+
outer_key_selector: Callable[[TItem], Any],
|
|
2079
|
+
inner_key_selector: Callable[[TInner], Any],
|
|
2080
|
+
result_selector: Callable[[TItem, FlpList[TInner]], TResult],
|
|
2081
|
+
) -> FlpIt[TResult]: ...
|
|
2082
|
+
|
|
2083
|
+
def group_join[TInner](
|
|
2084
|
+
self,
|
|
2085
|
+
inner: Iterable[TInner],
|
|
2086
|
+
outer_key_selector: Callable[[TItem], Any],
|
|
2087
|
+
inner_key_selector: Callable[[TInner], Any],
|
|
2088
|
+
result_selector: Callable[[TItem, FlpList[TInner]], Any] | _Sentinel = _SENTINEL,
|
|
2089
|
+
) -> FlpIt[Any]:
|
|
2090
|
+
return FlpIt(self.__list.data).group_join(inner, outer_key_selector, inner_key_selector, result_selector)
|
|
2091
|
+
|
|
1672
2092
|
def chunk(self, size: int) -> FlpIt[FlpList[TItem]]:
|
|
1673
2093
|
return FlpIt(self.__list.data).chunk(size)
|
|
1674
2094
|
|
|
@@ -1845,9 +2265,26 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1845
2265
|
) -> dict[Any, Any]:
|
|
1846
2266
|
return FlpIt(self.__list.data).to_dictionary(key_selector, element_selector)
|
|
1847
2267
|
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
2268
|
+
@overload
|
|
2269
|
+
def to_lookup[TKey](
|
|
2270
|
+
self, key_selector: Callable[[TItem], TKey], /
|
|
2271
|
+
) -> Lookup[TKey, TItem]: ...
|
|
2272
|
+
|
|
2273
|
+
@overload
|
|
2274
|
+
def to_lookup[TKey, TElement](
|
|
2275
|
+
self,
|
|
2276
|
+
key_selector: Callable[[TItem], TKey],
|
|
2277
|
+
element_selector: Callable[[TItem], TElement],
|
|
2278
|
+
/,
|
|
2279
|
+
) -> Lookup[TKey, TElement]: ...
|
|
2280
|
+
|
|
2281
|
+
def to_lookup(
|
|
2282
|
+
self,
|
|
2283
|
+
key_selector: Callable[[TItem], Any],
|
|
2284
|
+
element_selector: Callable[[TItem], Any] | _Sentinel = _SENTINEL,
|
|
2285
|
+
) -> Lookup[Any, Any]:
|
|
2286
|
+
return FlpIt(self.__list.data).to_lookup(key_selector, element_selector)
|
|
2287
|
+
|
|
1851
2288
|
def to_list(self) -> FlpList[TItem]:
|
|
1852
2289
|
"""Explicitly returns a shallow copy instance to isolate mutations."""
|
|
1853
2290
|
return FlpList(self.__list.data.copy())
|
|
@@ -1876,3 +2313,4 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1876
2313
|
|
|
1877
2314
|
# I hate it, but Python being Python
|
|
1878
2315
|
from ._grouping import Grouping
|
|
2316
|
+
from ._lookup import Lookup
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|