flpit 0.3.1.dev6__tar.gz → 0.3.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flpit
3
- Version: 0.3.1.dev6
3
+ Version: 0.3.3
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 all three yield `JoinTuple(outer, inner)`.
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()` has no .NET LINQ equivalent. It yields the `left_join()` rows in outer order, followed by every inner element that was never matched (in inner order).
335
- * Argument validation is eager (`InnerNoneError`, `OuterKeySelectorNoneError`, `InnerKeySelectorNoneError`, `ResultSelectorNoneError`); everything else is deferred.
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
- `join()`, `left_join()` and `full_join()` build a hash lookup of the `inner` sequence when enumeration starts and stream the outer sequence (O(N + M)).
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 | 4733 |
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 all three yield `JoinTuple(outer, inner)`.
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()` has no .NET LINQ equivalent. It yields the `left_join()` rows in outer order, followed by every inner element that was never matched (in inner order).
311
- * Argument validation is eager (`InnerNoneError`, `OuterKeySelectorNoneError`, `InnerKeySelectorNoneError`, `ResultSelectorNoneError`); everything else is deferred.
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
- `join()`, `left_join()` and `full_join()` build a hash lookup of the `inner` sequence when enumeration starts and stream the outer sequence (O(N + M)).
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 | 4733 |
553
+ | GRAND TOTALS | 7660 |
488
554
  ================================================================================
489
555
  ```
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "flpit"
3
- version = "0.3.1.dev6"
3
+ version = "0.3.3"
4
4
  description = "Fluent LINQ for Python — flip your iterables"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -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
- from collections import UserList
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")
@@ -290,6 +296,19 @@ def dotnet_context() -> AbstractContextManager[decimal.Context]:
290
296
  return decimal.localcontext(ctx)
291
297
 
292
298
 
299
+ def _decimal_mean(total: Decimal, count: int) -> Decimal:
300
+ """
301
+ ``total / count`` like .NET ``decimal`` division: rounded to 29 significant digits instead of
302
+ raising ``Inexact`` (the summation context traps ``Inexact`` only to detect decimal overflow).
303
+ """
304
+ ctx = decimal.getcontext().copy()
305
+ ctx.prec = max(ctx.prec, 29)
306
+ ctx.traps[Inexact] = False
307
+ ctx.traps[Overflow] = True
308
+ with decimal.localcontext(ctx):
309
+ return total / Decimal(count)
310
+
311
+
293
312
  class _FactoryIterable[TItem](Iterable[TItem]):
294
313
  """
295
314
  Wraps a generator factory function into a clean Iterable[T].
@@ -351,7 +370,7 @@ def _validate_join_args(
351
370
  inner_key_selector: Any,
352
371
  result_selector: Any,
353
372
  ) -> None:
354
- """Eager argument validation shared by join / left_join / full_join (mirrors .NET)."""
373
+ """Eager argument validation shared by join / left_join / full_join / group_join (mirrors .NET)."""
355
374
  if inner is None:
356
375
  raise InnerNoneError()
357
376
  if outer_key_selector is None:
@@ -496,6 +515,20 @@ class FlpIt[TItem](Iterable[TItem]):
496
515
  raise SelectorNoneError()
497
516
  return FlpIt(_SelectIterable(self._node_source(), selector))
498
517
 
518
+ def index(self) -> FlpIt[IndexTuple[TItem]]:
519
+ """
520
+ Returns an enumerable that incorporates the element's index into a tuple (.NET 9 ``Index()``).
521
+
522
+ Yields ``IndexTuple(index, item)`` for every element, with ``index`` starting at 0. Execution is
523
+ deferred and the source is streamed element by element; being a plain ``tuple`` subclass the
524
+ result unpacks as ``for i, item in query.index()``.
525
+ """
526
+ def _generator() -> Iterator[IndexTuple[TItem]]:
527
+ for position, item in enumerate(self):
528
+ yield IndexTuple(position, item)
529
+
530
+ return FlpIt(_FactoryIterable(_generator))
531
+
499
532
  def select_many[TResult](
500
533
  self, selector: Callable[[TItem], Iterable[TResult]]
501
534
  ) -> FlpIt[TResult]:
@@ -544,15 +577,80 @@ class FlpIt[TItem](Iterable[TItem]):
544
577
 
545
578
  return FlpIt(_FactoryIterable(_generator))
546
579
 
580
+ def skip_last(self, count: int) -> "FlpIt[TItem]":
581
+ """
582
+ Returns the elements of the sequence with the last ``count`` elements omitted (.NET ``SkipLast()``).
583
+
584
+ Execution is deferred and the source is streamed: at most ``count`` elements are read ahead of
585
+ the element currently being yielded, so the operator buffers no more than ``count`` elements.
586
+ A ``count`` of zero or less omits nothing and returns the sequence unchanged.
587
+ """
588
+ if count <= 0:
589
+ return self
590
+
591
+ def _generator() -> Iterator[TItem]:
592
+ queue: deque[TItem] = deque()
593
+ for item in self:
594
+ if len(queue) == count:
595
+ yield queue.popleft()
596
+ queue.append(item)
597
+
598
+ return FlpIt(_FactoryIterable(_generator))
599
+
600
+ def take_last(self, count: int) -> "FlpIt[TItem]":
601
+ """
602
+ Returns the last ``count`` elements of the sequence (.NET ``TakeLast()``).
603
+
604
+ Execution is deferred until the returned sequence is enumerated. The last elements are only known
605
+ once the end of the source is reached, so enumeration first consumes the whole source (keeping
606
+ at most ``count`` elements in memory) and then yields the retained elements in source order.
607
+ A ``count`` of zero or less yields an empty sequence without touching the source.
608
+ """
609
+ if count <= 0:
610
+ return FlpIt(())
611
+
612
+ def _generator() -> Iterator[TItem]:
613
+ # deque() cannot hold a maxlen above sys.maxsize; such a count keeps everything anyway.
614
+ yield from deque(self, maxlen=min(count, sys.maxsize))
615
+
616
+ return FlpIt(_FactoryIterable(_generator))
617
+
618
+ def default_if_empty[TResult](self, default: TResult) -> FlpIt[TItem | TResult]:
619
+ """
620
+ Returns the elements of the sequence, or a sequence containing only ``default`` if the
621
+ sequence is empty (.NET ``DefaultIfEmpty(defaultValue)``).
622
+
623
+ Execution is deferred and the source is streamed; it is enumerated once per enumeration of
624
+ the result. ``default`` is mandatory: Python has no ``default(T)``, so the parameterless
625
+ .NET overload is not provided.
626
+ """
627
+ def _generator() -> Iterator[TItem | TResult]:
628
+ iterator = iter(self)
629
+ for item in iterator:
630
+ yield item
631
+ yield from iterator
632
+ return
633
+ yield default
634
+
635
+ return FlpIt(_FactoryIterable(_generator))
636
+
547
637
  def cast[TResult](self, target_type: Type[TResult]) -> FlpIt[TResult]:
548
638
  """Casts elements to a specified type or raises TypeError if cast fails."""
639
+ _VALUE_TYPES = (int, float, bool, complex)
640
+
549
641
  def _generator() -> Iterator[TResult]:
550
642
  for item in self:
643
+ if item is None:
644
+ if target_type in _VALUE_TYPES:
645
+ raise AttributeError("Cannot unbox None to a non-nullable value type")
646
+ yield item
647
+ continue
648
+
551
649
  if not isinstance(item, target_type):
552
650
  raise TypeError(
553
651
  f"Cannot cast element {item!r} of type {type(item).__name__} to {target_type.__name__}"
554
652
  )
555
- yield item # type: ignore[misc]
653
+ yield item
556
654
 
557
655
  return FlpIt(_FactoryIterable(_generator))
558
656
 
@@ -560,7 +658,7 @@ class FlpIt[TItem](Iterable[TItem]):
560
658
  """Filters the elements of an Iterable based on a specified type."""
561
659
  def _generator() -> Iterator[TResult]:
562
660
  for item in self:
563
- if isinstance(item, target_type):
661
+ if item is not None and isinstance(item, target_type):
564
662
  yield item # type: ignore[misc]
565
663
 
566
664
  return FlpIt(_FactoryIterable(_generator))
@@ -593,6 +691,94 @@ class FlpIt[TItem](Iterable[TItem]):
593
691
 
594
692
  return FlpIt(_FactoryIterable(_generator))
595
693
 
694
+ def except_(self, second: Iterable[TItem]) -> FlpIt[TItem]:
695
+ """Produces the set difference of two sequences (deferred).
696
+
697
+ Named ``except_`` because ``except`` is a reserved word in Python.
698
+ Returns the distinct elements of this sequence that do not appear in
699
+ ``second``, in source order. ``second`` is fully enumerated on first iteration.
700
+ """
701
+ if second is None:
702
+ raise SecondNoneError()
703
+
704
+ def _generator() -> Iterator[TItem]:
705
+ seen: Set[TItem] = set(second)
706
+ for item in self:
707
+ if item not in seen:
708
+ seen.add(item)
709
+ yield item
710
+
711
+ return FlpIt(_FactoryIterable(_generator))
712
+
713
+ def except_by(
714
+ self,
715
+ second: Iterable[TKey],
716
+ key_selector: Callable[[TItem], TKey],
717
+ ) -> FlpIt[TItem]:
718
+ """Produces the set difference of two sequences according to a key selector (deferred).
719
+
720
+ Returns the elements of this sequence, distinct by key, whose key does not
721
+ appear in ``second``, in source order.
722
+ """
723
+ if second is None:
724
+ raise SecondNoneError()
725
+ if key_selector is None:
726
+ raise SelectorNoneError()
727
+
728
+ def _generator() -> Iterator[TItem]:
729
+ seen: Set[TKey] = set(second)
730
+ for item in self:
731
+ key = key_selector(item)
732
+ if key not in seen:
733
+ seen.add(key)
734
+ yield item
735
+
736
+ return FlpIt(_FactoryIterable(_generator))
737
+
738
+ def intersect(self, second: Iterable[TItem]) -> FlpIt[TItem]:
739
+ """Produces the set intersection of two sequences (deferred).
740
+
741
+ Returns the distinct elements of this sequence that also appear in
742
+ ``second``, in source order. ``second`` is fully enumerated on first
743
+ iteration, before the first element of this sequence is requested;
744
+ this sequence is then streamed.
745
+ """
746
+ if second is None:
747
+ raise SecondNoneError()
748
+
749
+ def _generator() -> Iterator[TItem]:
750
+ remaining: Set[TItem] = set(second)
751
+ for item in self:
752
+ if item in remaining:
753
+ remaining.remove(item)
754
+ yield item
755
+
756
+ return FlpIt(_FactoryIterable(_generator))
757
+
758
+ def union(self, second: Iterable[TItem]) -> FlpIt[TItem]:
759
+ """Produces the set union of two sequences (deferred).
760
+
761
+ Returns the distinct elements of this sequence followed by the distinct
762
+ elements of ``second`` that were not already produced, in encounter order.
763
+ Both sequences are streamed; ``second`` is not enumerated until this
764
+ sequence is exhausted.
765
+ """
766
+ if second is None:
767
+ raise SecondNoneError()
768
+
769
+ def _generator() -> Iterator[TItem]:
770
+ seen: Set[TItem] = set()
771
+ for item in self:
772
+ if item not in seen:
773
+ seen.add(item)
774
+ yield item
775
+ for item in second:
776
+ if item not in seen:
777
+ seen.add(item)
778
+ yield item
779
+
780
+ return FlpIt(_FactoryIterable(_generator))
781
+
596
782
  @overload
597
783
  def zip(self, second: Iterable[TOther]) -> FlpIt[ZipTuple[TItem, TOther]]: ...
598
784
 
@@ -752,24 +938,22 @@ class FlpIt[TItem](Iterable[TItem]):
752
938
  result_selector: Callable[[TItem | None, TInner | None], Any] | _Sentinel = _SENTINEL,
753
939
  ) -> FlpIt[Any]:
754
940
  """
755
- Full outer join (no .NET LINQ equivalent).
941
+ Full outer join (.NET 11 ``FullJoin``).
756
942
 
757
943
  Produces everything ``left_join`` does (unmatched outer elements paired with ``None``),
758
944
  followed by every inner element that was never matched by any outer element, paired with
759
- ``None`` as the outer element (``result_selector(None, inner)``), in inner order.
945
+ ``None`` as the outer element (``result_selector(None, inner)``), grouped by key in order of
946
+ first key appearance (like .NET, which walks its inner lookup).
760
947
  Elements with a ``None`` key never match and therefore always appear unmatched.
761
948
  The outer sequence is streamed; the inner sequence is buffered.
762
949
  """
763
950
  _validate_join_args(inner, outer_key_selector, inner_key_selector, result_selector)
764
951
 
765
952
  def _generator() -> Iterator[Any]:
766
- inner_items: list[tuple[Any, TInner]] = []
953
+ # Like .NET (Lookup.Create): None keys are kept, but never match.
767
954
  lookup: dict[Any, list[TInner]] = {}
768
955
  for inner_item in inner:
769
- inner_key = inner_key_selector(inner_item)
770
- inner_items.append((inner_key, inner_item))
771
- if inner_key is not None:
772
- lookup.setdefault(inner_key, []).append(inner_item)
956
+ lookup.setdefault(inner_key_selector(inner_item), []).append(inner_item)
773
957
 
774
958
  matched_keys: set[Any] = set()
775
959
  for outer_item in self:
@@ -788,12 +972,112 @@ class FlpIt[TItem](Iterable[TItem]):
788
972
  else:
789
973
  yield result_selector(outer_item, inner_item)
790
974
 
791
- for inner_key, inner_item in inner_items:
975
+ for inner_key, group in lookup.items():
792
976
  if inner_key is None or inner_key not in matched_keys:
977
+ for inner_item in group:
978
+ if result_selector is _SENTINEL:
979
+ yield JoinTuple(None, inner_item)
980
+ else:
981
+ yield result_selector(None, inner_item)
982
+
983
+ return FlpIt(_FactoryIterable(_generator))
984
+
985
+ @overload
986
+ def cross_join[TInner](
987
+ self,
988
+ inner: Iterable[TInner],
989
+ ) -> FlpIt[JoinTuple[TItem, TInner]]: ...
990
+
991
+ @overload
992
+ def cross_join[TResult, TInner](
993
+ self,
994
+ inner: Iterable[TInner],
995
+ result_selector: Callable[[TItem, TInner], TResult],
996
+ ) -> FlpIt[TResult]: ...
997
+
998
+ def cross_join[TInner](
999
+ self,
1000
+ inner: Iterable[TInner],
1001
+ result_selector: Callable[[TItem, TInner], Any] | _Sentinel = _SENTINEL,
1002
+ ) -> FlpIt[Any]:
1003
+ """
1004
+ Cross join (cartesian product; no .NET LINQ equivalent).
1005
+
1006
+ Produces one result per (outer, inner) pair, in outer order and, per outer element,
1007
+ in inner order. Without a result selector ``JoinTuple(outer, inner)`` is yielded.
1008
+ Arguments are validated eagerly. The outer sequence is streamed; ``inner`` is buffered
1009
+ once when enumeration starts, because it is traversed again for every outer element.
1010
+ If ``inner`` is empty the result is empty and the outer sequence is not enumerated.
1011
+ """
1012
+ if inner is None:
1013
+ raise InnerNoneError()
1014
+ if result_selector is None:
1015
+ raise ResultSelectorNoneError()
1016
+
1017
+ def _generator() -> Iterator[Any]:
1018
+ inner_items = list(inner)
1019
+ if not inner_items:
1020
+ return
1021
+ for outer_item in self:
1022
+ for inner_item in inner_items:
793
1023
  if result_selector is _SENTINEL:
794
- yield JoinTuple(None, inner_item)
1024
+ yield JoinTuple(outer_item, inner_item)
795
1025
  else:
796
- yield result_selector(None, inner_item)
1026
+ yield result_selector(outer_item, inner_item)
1027
+
1028
+ return FlpIt(_FactoryIterable(_generator))
1029
+
1030
+ @overload
1031
+ def group_join[TInner](
1032
+ self,
1033
+ inner: Iterable[TInner],
1034
+ outer_key_selector: Callable[[TItem], Any],
1035
+ inner_key_selector: Callable[[TInner], Any],
1036
+ ) -> FlpIt[Grouping[TItem, TInner]]: ...
1037
+
1038
+ @overload
1039
+ def group_join[TResult, TInner](
1040
+ self,
1041
+ inner: Iterable[TInner],
1042
+ outer_key_selector: Callable[[TItem], Any],
1043
+ inner_key_selector: Callable[[TInner], Any],
1044
+ result_selector: Callable[[TItem, FlpList[TInner]], TResult],
1045
+ ) -> FlpIt[TResult]: ...
1046
+
1047
+ def group_join[TInner](
1048
+ self,
1049
+ inner: Iterable[TInner],
1050
+ outer_key_selector: Callable[[TItem], Any],
1051
+ inner_key_selector: Callable[[TInner], Any],
1052
+ result_selector: Callable[[TItem, FlpList[TInner]], Any] | _Sentinel = _SENTINEL,
1053
+ ) -> FlpIt[Any]:
1054
+ """
1055
+ Group join (.NET ``GroupJoin``): correlates each outer element with the group of its matching inner elements.
1056
+
1057
+ Yields exactly one result per outer element, in outer order, so an outer element without a match
1058
+ still appears, paired with an empty group. The group holds the matching inner elements in inner order
1059
+ and can be enumerated repeatedly. Without a result selector a ``Grouping`` is yielded, whose ``key`` is
1060
+ the outer element and whose items are its matching inner elements; with one,
1061
+ ``result_selector(outer, group)`` is yielded with ``group`` being a ``FlpList`` of the matches.
1062
+ Elements whose key is ``None`` never match (an outer element with a ``None`` key gets an empty group).
1063
+
1064
+ Arguments are validated eagerly. The outer sequence is streamed; like .NET, ``inner`` is buffered
1065
+ into a hash lookup (O(N + M)) only once the outer sequence yields its first element, so an empty outer
1066
+ sequence never enumerates ``inner``.
1067
+ """
1068
+ _validate_join_args(inner, outer_key_selector, inner_key_selector, result_selector)
1069
+
1070
+ def _generator() -> Iterator[Any]:
1071
+ lookup: dict[Any, list[TInner]] | None = None
1072
+ for outer_item in self:
1073
+ if lookup is None:
1074
+ lookup = _build_lookup(inner, inner_key_selector)
1075
+ key = outer_key_selector(outer_item)
1076
+ matches = () if key is None else lookup.get(key, ())
1077
+ if result_selector is _SENTINEL:
1078
+ yield Grouping(outer_item, matches)
1079
+ else:
1080
+ yield result_selector(outer_item, FlpList(matches))
797
1081
 
798
1082
  return FlpIt(_FactoryIterable(_generator))
799
1083
 
@@ -993,7 +1277,7 @@ class FlpIt[TItem](Iterable[TItem]):
993
1277
  return None
994
1278
 
995
1279
  if isinstance(total, Decimal):
996
- return total / Decimal(count)
1280
+ return _decimal_mean(total, count)
997
1281
 
998
1282
  assert total is not None
999
1283
  assert isinstance(total, Decimal) or isinstance(total, int) or isinstance(total, float)
@@ -1149,13 +1433,59 @@ class FlpIt[TItem](Iterable[TItem]):
1149
1433
  result: dict[Any, Any] = {}
1150
1434
  for item in self:
1151
1435
  key = key_selector(item)
1436
+
1437
+ if key is None:
1438
+ raise ArgumentNullError("Value cannot be null. (Parameter 'key')")
1439
+
1152
1440
  if key in result:
1153
- raise ValueError(f"An item with the same key has already been added. Key: {key!r}")
1441
+ raise ArgumentError(
1442
+ f"An item with the same key has already been added. Key: {key!r}"
1443
+ )
1444
+
1154
1445
  value = item if element_selector is _SENTINEL else element_selector(item)
1155
1446
  result[key] = value
1156
1447
 
1157
1448
  return result
1158
1449
 
1450
+ @overload
1451
+ def to_lookup[TKey](
1452
+ self, key_selector: Callable[[TItem], TKey], /
1453
+ ) -> Lookup[TKey, TItem]: ...
1454
+
1455
+ @overload
1456
+ def to_lookup[TKey, TElement](
1457
+ self,
1458
+ key_selector: Callable[[TItem], TKey],
1459
+ element_selector: Callable[[TItem], TElement],
1460
+ /,
1461
+ ) -> Lookup[TKey, TElement]: ...
1462
+
1463
+ def to_lookup(
1464
+ self,
1465
+ key_selector: Callable[[TItem], Any],
1466
+ element_selector: Callable[[TItem], Any] | _Sentinel = _SENTINEL,
1467
+ ) -> Lookup[Any, Any]:
1468
+ """
1469
+ Materializes the sequence as a ``Lookup`` (.NET ``ToLookup``): a read-only one-to-many map of keys
1470
+ to groupings, in order of first key appearance. ``None`` is a valid key; missing keys index to an
1471
+ empty sequence. Keys are compared with ``==`` / ``hash``; comparer overloads are not provided yet.
1472
+ """
1473
+ if key_selector is None:
1474
+ raise SelectorNoneError()
1475
+ if element_selector is None:
1476
+ raise ElementSelectorNoneError()
1477
+
1478
+ groups: dict[Any, list[Any]] = {}
1479
+ if element_selector is _SENTINEL:
1480
+ for item in self:
1481
+ groups.setdefault(key_selector(item), []).append(item)
1482
+ else:
1483
+ for item in self:
1484
+ key = key_selector(item)
1485
+ groups.setdefault(key, []).append(element_selector(item))
1486
+
1487
+ return Lookup({k: Grouping(k, v) for k, v in groups.items()})
1488
+
1159
1489
  def to_list(self) -> FlpList[TItem]:
1160
1490
  """Explicitly materializes the query into a FlpList."""
1161
1491
  return FlpList[TItem](self)
@@ -1549,6 +1879,9 @@ class FlpList[TItem](Collection[TItem]):
1549
1879
  def select[TResult](self, selector: Callable[[TItem], TResult]) -> FlpIt[TResult]:
1550
1880
  return FlpIt(self.__list.data).select(selector)
1551
1881
 
1882
+ def index(self) -> FlpIt[IndexTuple[TItem]]:
1883
+ return FlpIt(self.__list.data).index()
1884
+
1552
1885
  def select_many[TResult](
1553
1886
  self, selector: Callable[[TItem], Iterable[TResult]]
1554
1887
  ) -> FlpIt[TResult]:
@@ -1560,6 +1893,43 @@ class FlpList[TItem](Collection[TItem]):
1560
1893
  def take(self, count: int) -> FlpIt[TItem]:
1561
1894
  return FlpIt(self.__list.data).take(count)
1562
1895
 
1896
+ def skip_last(self, count: int) -> FlpIt[TItem]:
1897
+ data = self.__list.data
1898
+
1899
+ if count <= 0:
1900
+ return FlpIt(data)
1901
+
1902
+ def _generator() -> Iterator[TItem]:
1903
+ end = max(0, len(data) - max(0, count))
1904
+ yield from islice(data, end)
1905
+
1906
+ return FlpIt(
1907
+ _FactoryIterable(_generator)
1908
+ )
1909
+
1910
+ def take_last(self, count: int) -> FlpIt[TItem]:
1911
+ data = self.__list.data
1912
+
1913
+ if count <= 0:
1914
+ return FlpIt(())
1915
+
1916
+ def _generator() -> Iterator[TItem]:
1917
+ yield from islice(data, max(0, len(data) - count), None)
1918
+
1919
+ return FlpIt(_FactoryIterable(_generator))
1920
+
1921
+ def default_if_empty[TResult](self, default: TResult) -> FlpIt[TItem | TResult]:
1922
+ data = self.__list.data
1923
+
1924
+ def _generator() -> Iterator[TItem | TResult]:
1925
+ # Emptiness is checked when enumeration starts, so later mutations of the list are observed.
1926
+ if data:
1927
+ yield from data
1928
+ else:
1929
+ yield default
1930
+
1931
+ return FlpIt(_FactoryIterable(_generator))
1932
+
1563
1933
  def cast[TResult](self, target_type: Type[TResult]) -> FlpIt[TResult]:
1564
1934
  return FlpIt(self.__list.data).cast(target_type)
1565
1935
 
@@ -1574,6 +1944,22 @@ class FlpList[TItem](Collection[TItem]):
1574
1944
  ) -> FlpIt[TItem]:
1575
1945
  return FlpIt(self.__list.data).distinct_by(key_selector)
1576
1946
 
1947
+ def except_(self, second: Iterable[TItem]) -> FlpIt[TItem]:
1948
+ return FlpIt(self.__list.data).except_(second)
1949
+
1950
+ def except_by(
1951
+ self,
1952
+ second: Iterable[TKey],
1953
+ key_selector: Callable[[TItem], TKey],
1954
+ ) -> FlpIt[TItem]:
1955
+ return FlpIt(self.__list.data).except_by(second, key_selector)
1956
+
1957
+ def intersect(self, second: Iterable[TItem]) -> FlpIt[TItem]:
1958
+ return FlpIt(self.__list.data).intersect(second)
1959
+
1960
+ def union(self, second: Iterable[TItem]) -> FlpIt[TItem]:
1961
+ return FlpIt(self.__list.data).union(second)
1962
+
1577
1963
  @overload
1578
1964
  def zip(self, second: Iterable[TOther]) -> FlpIt[ZipTuple[TItem, TOther]]: ...
1579
1965
 
@@ -1669,6 +2055,52 @@ class FlpList[TItem](Collection[TItem]):
1669
2055
  ) -> FlpIt[Any]:
1670
2056
  return FlpIt(self.__list.data).full_join(inner, outer_key_selector, inner_key_selector, result_selector)
1671
2057
 
2058
+ @overload
2059
+ def cross_join[TInner](
2060
+ self,
2061
+ inner: Iterable[TInner],
2062
+ ) -> FlpIt[JoinTuple[TItem, TInner]]: ...
2063
+
2064
+ @overload
2065
+ def cross_join[TResult, TInner](
2066
+ self,
2067
+ inner: Iterable[TInner],
2068
+ result_selector: Callable[[TItem, TInner], TResult],
2069
+ ) -> FlpIt[TResult]: ...
2070
+
2071
+ def cross_join[TInner](
2072
+ self,
2073
+ inner: Iterable[TInner],
2074
+ result_selector: Callable[[TItem, TInner], Any] | _Sentinel = _SENTINEL,
2075
+ ) -> FlpIt[Any]:
2076
+ return FlpIt(self.__list.data).cross_join(inner, result_selector)
2077
+
2078
+ @overload
2079
+ def group_join[TInner](
2080
+ self,
2081
+ inner: Iterable[TInner],
2082
+ outer_key_selector: Callable[[TItem], Any],
2083
+ inner_key_selector: Callable[[TInner], Any],
2084
+ ) -> FlpIt[Grouping[TItem, TInner]]: ...
2085
+
2086
+ @overload
2087
+ def group_join[TResult, TInner](
2088
+ self,
2089
+ inner: Iterable[TInner],
2090
+ outer_key_selector: Callable[[TItem], Any],
2091
+ inner_key_selector: Callable[[TInner], Any],
2092
+ result_selector: Callable[[TItem, FlpList[TInner]], TResult],
2093
+ ) -> FlpIt[TResult]: ...
2094
+
2095
+ def group_join[TInner](
2096
+ self,
2097
+ inner: Iterable[TInner],
2098
+ outer_key_selector: Callable[[TItem], Any],
2099
+ inner_key_selector: Callable[[TInner], Any],
2100
+ result_selector: Callable[[TItem, FlpList[TInner]], Any] | _Sentinel = _SENTINEL,
2101
+ ) -> FlpIt[Any]:
2102
+ return FlpIt(self.__list.data).group_join(inner, outer_key_selector, inner_key_selector, result_selector)
2103
+
1672
2104
  def chunk(self, size: int) -> FlpIt[FlpList[TItem]]:
1673
2105
  return FlpIt(self.__list.data).chunk(size)
1674
2106
 
@@ -1845,9 +2277,26 @@ class FlpList[TItem](Collection[TItem]):
1845
2277
  ) -> dict[Any, Any]:
1846
2278
  return FlpIt(self.__list.data).to_dictionary(key_selector, element_selector)
1847
2279
 
1848
- def to_list(self) -> FlpList[TItem]:
1849
- """Explicitly returns a shallow copy instance to isolate mutations."""
1850
- return FlpList(self.__list.data.copy())
2280
+ @overload
2281
+ def to_lookup[TKey](
2282
+ self, key_selector: Callable[[TItem], TKey], /
2283
+ ) -> Lookup[TKey, TItem]: ...
2284
+
2285
+ @overload
2286
+ def to_lookup[TKey, TElement](
2287
+ self,
2288
+ key_selector: Callable[[TItem], TKey],
2289
+ element_selector: Callable[[TItem], TElement],
2290
+ /,
2291
+ ) -> Lookup[TKey, TElement]: ...
2292
+
2293
+ def to_lookup(
2294
+ self,
2295
+ key_selector: Callable[[TItem], Any],
2296
+ element_selector: Callable[[TItem], Any] | _Sentinel = _SENTINEL,
2297
+ ) -> Lookup[Any, Any]:
2298
+ return FlpIt(self.__list.data).to_lookup(key_selector, element_selector)
2299
+
1851
2300
  def to_list(self) -> FlpList[TItem]:
1852
2301
  """Explicitly returns a shallow copy instance to isolate mutations."""
1853
2302
  return FlpList(self.__list.data.copy())
@@ -1876,3 +2325,4 @@ class FlpList[TItem](Collection[TItem]):
1876
2325
 
1877
2326
  # I hate it, but Python being Python
1878
2327
  from ._grouping import Grouping
2328
+ 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