pyochain 0.5.31__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.

Potentially problematic release.


This version of pyochain might be problematic. Click here for more details.

Files changed (32) hide show
  1. pyochain-0.5.31/PKG-INFO +261 -0
  2. pyochain-0.5.31/README.md +251 -0
  3. pyochain-0.5.31/pyproject.toml +35 -0
  4. pyochain-0.5.31/src/pyochain/__init__.py +5 -0
  5. pyochain-0.5.31/src/pyochain/_core/__init__.py +23 -0
  6. pyochain-0.5.31/src/pyochain/_core/_format.py +34 -0
  7. pyochain-0.5.31/src/pyochain/_core/_main.py +205 -0
  8. pyochain-0.5.31/src/pyochain/_core/_protocols.py +38 -0
  9. pyochain-0.5.31/src/pyochain/_dict/__init__.py +3 -0
  10. pyochain-0.5.31/src/pyochain/_dict/_filters.py +268 -0
  11. pyochain-0.5.31/src/pyochain/_dict/_groups.py +175 -0
  12. pyochain-0.5.31/src/pyochain/_dict/_iter.py +135 -0
  13. pyochain-0.5.31/src/pyochain/_dict/_joins.py +139 -0
  14. pyochain-0.5.31/src/pyochain/_dict/_main.py +113 -0
  15. pyochain-0.5.31/src/pyochain/_dict/_maps.py +142 -0
  16. pyochain-0.5.31/src/pyochain/_dict/_nested.py +272 -0
  17. pyochain-0.5.31/src/pyochain/_dict/_process.py +204 -0
  18. pyochain-0.5.31/src/pyochain/_iter/__init__.py +3 -0
  19. pyochain-0.5.31/src/pyochain/_iter/_aggregations.py +324 -0
  20. pyochain-0.5.31/src/pyochain/_iter/_booleans.py +227 -0
  21. pyochain-0.5.31/src/pyochain/_iter/_dicts.py +243 -0
  22. pyochain-0.5.31/src/pyochain/_iter/_eager.py +233 -0
  23. pyochain-0.5.31/src/pyochain/_iter/_filters.py +510 -0
  24. pyochain-0.5.31/src/pyochain/_iter/_joins.py +404 -0
  25. pyochain-0.5.31/src/pyochain/_iter/_lists.py +308 -0
  26. pyochain-0.5.31/src/pyochain/_iter/_main.py +466 -0
  27. pyochain-0.5.31/src/pyochain/_iter/_maps.py +374 -0
  28. pyochain-0.5.31/src/pyochain/_iter/_partitions.py +145 -0
  29. pyochain-0.5.31/src/pyochain/_iter/_process.py +366 -0
  30. pyochain-0.5.31/src/pyochain/_iter/_rolling.py +241 -0
  31. pyochain-0.5.31/src/pyochain/_iter/_tuples.py +326 -0
  32. pyochain-0.5.31/src/pyochain/py.typed +0 -0
@@ -0,0 +1,261 @@
1
+ Metadata-Version: 2.3
2
+ Name: pyochain
3
+ Version: 0.5.31
4
+ Summary: Method chaining for iterables and dictionaries in Python.
5
+ Requires-Dist: cytoolz>=1.0.1
6
+ Requires-Dist: more-itertools>=10.8.0
7
+ Requires-Dist: rolling>=0.5.0
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+
11
+ # pyochain ⛓️
12
+
13
+ **_Functional-style method chaining for Python data structures._**
14
+
15
+ `pyochain` brings a fluent, declarative API inspired by Rust's `Iterator` and DataFrame libraries like Polars to your everyday Python iterables and dictionaries.
16
+
17
+ Manipulate data through composable chains of operations, enhancing readability and reducing boilerplate.
18
+
19
+ ## Notice on Stability ⚠️
20
+
21
+ `pyochain` is currently in early development (< 1.0), and the API may undergo significant changes multiple times before reaching a stable 1.0 release.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ uv add pyochain
27
+ ```
28
+
29
+ ## API Reference 📖
30
+
31
+ The full API reference can be found at:
32
+ <https://outsquarecapital.github.io/pyochain/>
33
+
34
+ ## Overview
35
+
36
+ ### Philosophy
37
+
38
+ * **Declarative over Imperative:** Replace explicit `for` and `while` loops with sequences of high-level operations (map, filter, group, join...).
39
+ * **Fluent Chaining:** Each method transforms the data and returns a new wrapper instance, allowing for seamless chaining.
40
+ * **Lazy and Eager:** `Iter` operates lazily for efficiency on large or infinite sequences, while `Seq` represents materialized sequences for eager operations.
41
+ * **100% Type-safe:** Extensive use of generics and overloads ensures type safety and improves developer experience.
42
+ * **Documentation-first:** Each method is thoroughly documented with clear explanations, and usage examples. Before any commit is made, each docstring is automatically tested to ensure accuracy. This also allows for a convenient experience in IDEs, where developers can easily access documentation with a simple hover of the mouse.
43
+ * **Functional paradigm:** Design encourages building complex data transformations by composing simple, reusable functions on known buildings blocks, rather than implementing customs classes each time.
44
+
45
+ ### Inspirations
46
+
47
+ * **Rust's language and Rust `Iterator` Trait:** Emulate naming conventions (`from_()`, `into()`) and leverage concepts from Rust's powerful iterator traits (method chaining, lazy evaluation) to bring similar expressiveness to Python.
48
+ * **Python iterators libraries:** Libraries like `rolling`, `cytoolz`, and `more-itertools` provided ideas, inspiration, and implementations for many of the iterator methods.
49
+ * **PyFunctional:** Although not directly used (because I started writing pyochain before discovering it), also shares similar goals and ideas.
50
+
51
+ ### Core Components
52
+
53
+ #### `Iter[T]`
54
+
55
+ To instantiate it, wrap a Python `Iterator` or `Generator`, or take any Iterable (`list`, `tuple`, etc...) and call Iter.from_ (which will call the builtin `iter()` on it).
56
+
57
+ All operations that return a new `Iter` are **lazy**, consuming the underlying iterator on demand.
58
+
59
+ Provides a vast array of methods for transformation, filtering, aggregation, joining, etc..
60
+
61
+ #### `Seq[T]`
62
+
63
+ Wraps a Python `Sequence` (`list`, `tuple`...), and represents **eagerly** evaluated data.
64
+
65
+ Exposes a subset of the `Iter` methods who operate on the full dataset (e.g., `sort`, `union`) or who aggregate it.
66
+
67
+ It is most useful when you need to reuse the data multiple times without re-iterating it.
68
+
69
+ Use `.iter()` to switch back to lazy processing.
70
+
71
+ #### `Dict[K, V]`
72
+
73
+ Wraps a Python `dict` (or any Mapping via ``Dict.from_``) and provides chainable methods specific to dictionaries (manipulating keys, values, items, nesting, joins, grouping).
74
+
75
+ Promote immutability by returning new `Dict` instances on each operation, and avoiding in-place modifications.
76
+
77
+ Can work easily on known data structure (e.g `dict[str, int]`), with methods like `map_values`, `filter_keys`, etc., who works on the whole `dict` in a performant way, mostly thanks to `cytoolz` functions.
78
+
79
+ But `Dict` can work also as well as on "irregular" structures (e.g., `dict[Any, Any]`, TypedDict, etc..), by providing a set of utilities for working with nested data, including:
80
+
81
+ * `pluck` to extract multiple fields at once.
82
+ * `flatten` to collapse nested structures into a single level.
83
+
84
+ #### `Wrapper[T]`
85
+
86
+ A generic wrapper for any Python object, allowing integration into `pyochain`'s fluent style using `pipe`, `apply`, and `into`.
87
+
88
+ Can be for example used to wrap numpy arrays, json outputs from requests, or any custom class instance, as a way to integrate them into a chain of operations, rather than breaking the chain to reference intermediate variables.
89
+
90
+ ### Core Piping Methods
91
+
92
+ All wrappers inherit from `CommonBase`:
93
+
94
+ * `into[**P, R](func: Callable[Concatenate[T, P]], *args: P.args, **kwargs: P.kwargs) -> R`
95
+ Passes the **unwrapped** data to `func` and returns the raw result (terminal).
96
+ * `apply[**P, R](func: Callable[Concatenate[T, P]], *args: P.args, **kwargs: P.kwargs) -> "CurrentWrapper"[R]`
97
+ Passes the **unwrapped** data to`func` and **re-wraps** the result for continued chaining.
98
+ * `pipe[**P, R](func: Callable[Concatenate[Self, P]], *args: P.args, **kwargs: P.kwargs) -> R`
99
+ Passes the **wrapped instance** (`self`) to `func` and returns the raw result (can be terminal).
100
+ * `println()`
101
+ Prints the unwrapped data and returns `self`.
102
+
103
+ ### Rich Lazy Iteration (`Iter`)
104
+
105
+ Leverage dozens of methods inspired by Rust's `Iterator`, `itertools`, `cytoolz`, and `more-itertools`.
106
+
107
+ ```python
108
+ import pyochain as pc
109
+
110
+ result = (
111
+ pc.Iter.from_count(1) # Infinite iterator: 1, 2, 3, ...
112
+ .filter(lambda x: x % 2 != 0) # Keep odd numbers: 1, 3, 5, ...
113
+ .map(lambda x: x * x) # Square them: 1, 9, 25, ...
114
+ .take(5) # Take the first 5: 1, 9, 25, 49, 81
115
+ .into(list) # Consume into a list
116
+ )
117
+ # result: [1, 9, 25, 49, 81]
118
+ ```
119
+
120
+ ### Typing enforcement
121
+
122
+ Each method and class make extensive use of generics, type hints, and overloads (when necessary) to ensure type safety and improve developer experience.
123
+
124
+ Since there's much less need for intermediate variables, the developper don't have to annotate them as much, whilst still keeping a type-safe codebase.
125
+
126
+ ### Convenience mappers: itr and struct
127
+
128
+ Operate on iterables of iterables or iterables of dicts without leaving the chain.
129
+
130
+ ```python
131
+ import pyochain as pc
132
+
133
+ nested = pc.Iter.from_([[1, 2, 3], [4, 5]])
134
+ totals = nested.itr(lambda it: it.sum()).into(list)
135
+ # [6, 9]
136
+
137
+ records = pc.Iter.from_(
138
+ [
139
+ {"name": "Alice", "age": 30},
140
+ {"name": "Bob", "age": 25},
141
+ ]
142
+ )
143
+ names = records.struct(lambda d: d.pluck("name").unwrap()).into(list)
144
+ # ['Alice', 'Bob']
145
+ ```
146
+
147
+ ## Key Dependencies and credits
148
+
149
+ Most of the computations are done with implementations from the `cytoolz`, `more-itertools`, and `rolling` libraries.
150
+
151
+ An extensive use of the `itertools` stdlib module is also to be noted.
152
+
153
+ pyochain acts as a unifying API layer over these powerful tools.
154
+
155
+ <https://github.com/pytoolz/cytoolz>
156
+
157
+ <https://github.com/more-itertools/more-itertools>
158
+
159
+ <https://github.com/ajcr/rolling>
160
+
161
+ The stubs used for the developpement, made by the maintainer of pyochain, can be found here:
162
+
163
+ <https://github.com/py-stubs/cytoolz-stubs>
164
+
165
+ ---
166
+
167
+ ## Real-life simple example
168
+
169
+ In one of my project, I have to introspect some modules from plotly to get some lists of colors.
170
+
171
+ I want to check wether the colors are in hex format or not, and I want to get a dictionary of palettes.
172
+ We can see here that pyochain allow to keep the same style than polars, with method chaining, but for plain python objects.
173
+
174
+ Due to the freedom of python, multiple paradigms are implemented across libraries.
175
+
176
+ If you like the fluent, functional, chainable style, pyochain can help you to keep it across your codebase, rather than mixing object().method().method() and then another where it's [[... for ... in ...] ... ].
177
+
178
+ ```python
179
+
180
+ from types import ModuleType
181
+
182
+ import polars as pl
183
+ import pyochain as pc
184
+ from plotly.express.colors import cyclical, qualitative, sequential
185
+
186
+
187
+
188
+ MODULES: set[ModuleType] = {
189
+ sequential,
190
+ cyclical,
191
+ qualitative,
192
+ }
193
+
194
+ def get_palettes() -> pc.Dict[str, list[str]]:
195
+ clr = "color"
196
+ scl = "scale"
197
+ df: pl.DataFrame = (
198
+ pc.Iter.from_(MODULES)
199
+ .map(
200
+ lambda mod: pc.Dict.from_object(mod)
201
+ .filter_values(lambda v: isinstance(v, list))
202
+ .unwrap()
203
+ )
204
+ .into(pl.LazyFrame)
205
+ .unpivot(value_name=clr, variable_name=scl)
206
+ .drop_nulls()
207
+ .filter(
208
+ pl.col(clr)
209
+ .list.eval(pl.element().first().str.starts_with("#").alias("is_hex"))
210
+ .list.first()
211
+ )
212
+ .sort(scl)
213
+ .collect()
214
+ )
215
+ keys: list[str] = df.get_column(scl).to_list()
216
+ values: list[list[str]] = df.get_column(clr).to_list()
217
+ return pc.Iter.from_(keys).with_values(values)
218
+
219
+
220
+ # Ouput excerpt:
221
+ {'mygbm_r': ['#ef55f1',
222
+ '#c543fa',
223
+ '#9139fa',
224
+ '#6324f5',
225
+ '#2e21ea',
226
+ '#284ec8',
227
+ '#3d719a',
228
+ '#439064',
229
+ '#31ac28',
230
+ '#61c10b',
231
+ '#96d310',
232
+ '#c6e516',
233
+ '#f0ed35',
234
+ '#fcd471',
235
+ '#fbafa1',
236
+ '#fb84ce',
237
+ '#ef55f1']}
238
+ ```
239
+
240
+ However you can still easily go back with for loops when the readability is better this way.
241
+
242
+ In another place, I use this function to generate a Literal from the keys of the palettes.
243
+
244
+ ```python
245
+
246
+ from enum import StrEnum
247
+
248
+ class Text(StrEnum):
249
+ CONTENT = "Palettes = Literal[\n"
250
+ END_CONTENT = "]\n"
251
+ ...# rest of the class
252
+
253
+ def generate_palettes_literal() -> None:
254
+ literal_content: str = Text.CONTENT
255
+ for name in get_palettes().iter_keys().sort().unwrap():
256
+ literal_content += f' "{name}",\n'
257
+ literal_content += Text.END_CONTENT
258
+ ...# rest of the function
259
+ ```
260
+
261
+ Since I have to reference the literal_content variable in the for loop, This is more reasonnable to use a for loop here rather than a map + reduce approach.
@@ -0,0 +1,251 @@
1
+ # pyochain ⛓️
2
+
3
+ **_Functional-style method chaining for Python data structures._**
4
+
5
+ `pyochain` brings a fluent, declarative API inspired by Rust's `Iterator` and DataFrame libraries like Polars to your everyday Python iterables and dictionaries.
6
+
7
+ Manipulate data through composable chains of operations, enhancing readability and reducing boilerplate.
8
+
9
+ ## Notice on Stability ⚠️
10
+
11
+ `pyochain` is currently in early development (< 1.0), and the API may undergo significant changes multiple times before reaching a stable 1.0 release.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ uv add pyochain
17
+ ```
18
+
19
+ ## API Reference 📖
20
+
21
+ The full API reference can be found at:
22
+ <https://outsquarecapital.github.io/pyochain/>
23
+
24
+ ## Overview
25
+
26
+ ### Philosophy
27
+
28
+ * **Declarative over Imperative:** Replace explicit `for` and `while` loops with sequences of high-level operations (map, filter, group, join...).
29
+ * **Fluent Chaining:** Each method transforms the data and returns a new wrapper instance, allowing for seamless chaining.
30
+ * **Lazy and Eager:** `Iter` operates lazily for efficiency on large or infinite sequences, while `Seq` represents materialized sequences for eager operations.
31
+ * **100% Type-safe:** Extensive use of generics and overloads ensures type safety and improves developer experience.
32
+ * **Documentation-first:** Each method is thoroughly documented with clear explanations, and usage examples. Before any commit is made, each docstring is automatically tested to ensure accuracy. This also allows for a convenient experience in IDEs, where developers can easily access documentation with a simple hover of the mouse.
33
+ * **Functional paradigm:** Design encourages building complex data transformations by composing simple, reusable functions on known buildings blocks, rather than implementing customs classes each time.
34
+
35
+ ### Inspirations
36
+
37
+ * **Rust's language and Rust `Iterator` Trait:** Emulate naming conventions (`from_()`, `into()`) and leverage concepts from Rust's powerful iterator traits (method chaining, lazy evaluation) to bring similar expressiveness to Python.
38
+ * **Python iterators libraries:** Libraries like `rolling`, `cytoolz`, and `more-itertools` provided ideas, inspiration, and implementations for many of the iterator methods.
39
+ * **PyFunctional:** Although not directly used (because I started writing pyochain before discovering it), also shares similar goals and ideas.
40
+
41
+ ### Core Components
42
+
43
+ #### `Iter[T]`
44
+
45
+ To instantiate it, wrap a Python `Iterator` or `Generator`, or take any Iterable (`list`, `tuple`, etc...) and call Iter.from_ (which will call the builtin `iter()` on it).
46
+
47
+ All operations that return a new `Iter` are **lazy**, consuming the underlying iterator on demand.
48
+
49
+ Provides a vast array of methods for transformation, filtering, aggregation, joining, etc..
50
+
51
+ #### `Seq[T]`
52
+
53
+ Wraps a Python `Sequence` (`list`, `tuple`...), and represents **eagerly** evaluated data.
54
+
55
+ Exposes a subset of the `Iter` methods who operate on the full dataset (e.g., `sort`, `union`) or who aggregate it.
56
+
57
+ It is most useful when you need to reuse the data multiple times without re-iterating it.
58
+
59
+ Use `.iter()` to switch back to lazy processing.
60
+
61
+ #### `Dict[K, V]`
62
+
63
+ Wraps a Python `dict` (or any Mapping via ``Dict.from_``) and provides chainable methods specific to dictionaries (manipulating keys, values, items, nesting, joins, grouping).
64
+
65
+ Promote immutability by returning new `Dict` instances on each operation, and avoiding in-place modifications.
66
+
67
+ Can work easily on known data structure (e.g `dict[str, int]`), with methods like `map_values`, `filter_keys`, etc., who works on the whole `dict` in a performant way, mostly thanks to `cytoolz` functions.
68
+
69
+ But `Dict` can work also as well as on "irregular" structures (e.g., `dict[Any, Any]`, TypedDict, etc..), by providing a set of utilities for working with nested data, including:
70
+
71
+ * `pluck` to extract multiple fields at once.
72
+ * `flatten` to collapse nested structures into a single level.
73
+
74
+ #### `Wrapper[T]`
75
+
76
+ A generic wrapper for any Python object, allowing integration into `pyochain`'s fluent style using `pipe`, `apply`, and `into`.
77
+
78
+ Can be for example used to wrap numpy arrays, json outputs from requests, or any custom class instance, as a way to integrate them into a chain of operations, rather than breaking the chain to reference intermediate variables.
79
+
80
+ ### Core Piping Methods
81
+
82
+ All wrappers inherit from `CommonBase`:
83
+
84
+ * `into[**P, R](func: Callable[Concatenate[T, P]], *args: P.args, **kwargs: P.kwargs) -> R`
85
+ Passes the **unwrapped** data to `func` and returns the raw result (terminal).
86
+ * `apply[**P, R](func: Callable[Concatenate[T, P]], *args: P.args, **kwargs: P.kwargs) -> "CurrentWrapper"[R]`
87
+ Passes the **unwrapped** data to`func` and **re-wraps** the result for continued chaining.
88
+ * `pipe[**P, R](func: Callable[Concatenate[Self, P]], *args: P.args, **kwargs: P.kwargs) -> R`
89
+ Passes the **wrapped instance** (`self`) to `func` and returns the raw result (can be terminal).
90
+ * `println()`
91
+ Prints the unwrapped data and returns `self`.
92
+
93
+ ### Rich Lazy Iteration (`Iter`)
94
+
95
+ Leverage dozens of methods inspired by Rust's `Iterator`, `itertools`, `cytoolz`, and `more-itertools`.
96
+
97
+ ```python
98
+ import pyochain as pc
99
+
100
+ result = (
101
+ pc.Iter.from_count(1) # Infinite iterator: 1, 2, 3, ...
102
+ .filter(lambda x: x % 2 != 0) # Keep odd numbers: 1, 3, 5, ...
103
+ .map(lambda x: x * x) # Square them: 1, 9, 25, ...
104
+ .take(5) # Take the first 5: 1, 9, 25, 49, 81
105
+ .into(list) # Consume into a list
106
+ )
107
+ # result: [1, 9, 25, 49, 81]
108
+ ```
109
+
110
+ ### Typing enforcement
111
+
112
+ Each method and class make extensive use of generics, type hints, and overloads (when necessary) to ensure type safety and improve developer experience.
113
+
114
+ Since there's much less need for intermediate variables, the developper don't have to annotate them as much, whilst still keeping a type-safe codebase.
115
+
116
+ ### Convenience mappers: itr and struct
117
+
118
+ Operate on iterables of iterables or iterables of dicts without leaving the chain.
119
+
120
+ ```python
121
+ import pyochain as pc
122
+
123
+ nested = pc.Iter.from_([[1, 2, 3], [4, 5]])
124
+ totals = nested.itr(lambda it: it.sum()).into(list)
125
+ # [6, 9]
126
+
127
+ records = pc.Iter.from_(
128
+ [
129
+ {"name": "Alice", "age": 30},
130
+ {"name": "Bob", "age": 25},
131
+ ]
132
+ )
133
+ names = records.struct(lambda d: d.pluck("name").unwrap()).into(list)
134
+ # ['Alice', 'Bob']
135
+ ```
136
+
137
+ ## Key Dependencies and credits
138
+
139
+ Most of the computations are done with implementations from the `cytoolz`, `more-itertools`, and `rolling` libraries.
140
+
141
+ An extensive use of the `itertools` stdlib module is also to be noted.
142
+
143
+ pyochain acts as a unifying API layer over these powerful tools.
144
+
145
+ <https://github.com/pytoolz/cytoolz>
146
+
147
+ <https://github.com/more-itertools/more-itertools>
148
+
149
+ <https://github.com/ajcr/rolling>
150
+
151
+ The stubs used for the developpement, made by the maintainer of pyochain, can be found here:
152
+
153
+ <https://github.com/py-stubs/cytoolz-stubs>
154
+
155
+ ---
156
+
157
+ ## Real-life simple example
158
+
159
+ In one of my project, I have to introspect some modules from plotly to get some lists of colors.
160
+
161
+ I want to check wether the colors are in hex format or not, and I want to get a dictionary of palettes.
162
+ We can see here that pyochain allow to keep the same style than polars, with method chaining, but for plain python objects.
163
+
164
+ Due to the freedom of python, multiple paradigms are implemented across libraries.
165
+
166
+ If you like the fluent, functional, chainable style, pyochain can help you to keep it across your codebase, rather than mixing object().method().method() and then another where it's [[... for ... in ...] ... ].
167
+
168
+ ```python
169
+
170
+ from types import ModuleType
171
+
172
+ import polars as pl
173
+ import pyochain as pc
174
+ from plotly.express.colors import cyclical, qualitative, sequential
175
+
176
+
177
+
178
+ MODULES: set[ModuleType] = {
179
+ sequential,
180
+ cyclical,
181
+ qualitative,
182
+ }
183
+
184
+ def get_palettes() -> pc.Dict[str, list[str]]:
185
+ clr = "color"
186
+ scl = "scale"
187
+ df: pl.DataFrame = (
188
+ pc.Iter.from_(MODULES)
189
+ .map(
190
+ lambda mod: pc.Dict.from_object(mod)
191
+ .filter_values(lambda v: isinstance(v, list))
192
+ .unwrap()
193
+ )
194
+ .into(pl.LazyFrame)
195
+ .unpivot(value_name=clr, variable_name=scl)
196
+ .drop_nulls()
197
+ .filter(
198
+ pl.col(clr)
199
+ .list.eval(pl.element().first().str.starts_with("#").alias("is_hex"))
200
+ .list.first()
201
+ )
202
+ .sort(scl)
203
+ .collect()
204
+ )
205
+ keys: list[str] = df.get_column(scl).to_list()
206
+ values: list[list[str]] = df.get_column(clr).to_list()
207
+ return pc.Iter.from_(keys).with_values(values)
208
+
209
+
210
+ # Ouput excerpt:
211
+ {'mygbm_r': ['#ef55f1',
212
+ '#c543fa',
213
+ '#9139fa',
214
+ '#6324f5',
215
+ '#2e21ea',
216
+ '#284ec8',
217
+ '#3d719a',
218
+ '#439064',
219
+ '#31ac28',
220
+ '#61c10b',
221
+ '#96d310',
222
+ '#c6e516',
223
+ '#f0ed35',
224
+ '#fcd471',
225
+ '#fbafa1',
226
+ '#fb84ce',
227
+ '#ef55f1']}
228
+ ```
229
+
230
+ However you can still easily go back with for loops when the readability is better this way.
231
+
232
+ In another place, I use this function to generate a Literal from the keys of the palettes.
233
+
234
+ ```python
235
+
236
+ from enum import StrEnum
237
+
238
+ class Text(StrEnum):
239
+ CONTENT = "Palettes = Literal[\n"
240
+ END_CONTENT = "]\n"
241
+ ...# rest of the class
242
+
243
+ def generate_palettes_literal() -> None:
244
+ literal_content: str = Text.CONTENT
245
+ for name in get_palettes().iter_keys().sort().unwrap():
246
+ literal_content += f' "{name}",\n'
247
+ literal_content += Text.END_CONTENT
248
+ ...# rest of the function
249
+ ```
250
+
251
+ Since I have to reference the literal_content variable in the for loop, This is more reasonnable to use a for loop here rather than a map + reduce approach.
@@ -0,0 +1,35 @@
1
+ [project]
2
+ description = "Method chaining for iterables and dictionaries in Python."
3
+ name = "pyochain"
4
+ readme = "README.md"
5
+ requires-python = ">=3.12"
6
+ version = "0.5.31"
7
+
8
+ dependencies = ["cytoolz>=1.0.1", "more-itertools>=10.8.0", "rolling>=0.5.0"]
9
+
10
+ [dependency-groups]
11
+ dev = [
12
+ "doctester",
13
+ "griffe>=1.14.0",
14
+ "mkdocs>=1.6.1",
15
+ "mkdocs-autorefs>=1.4.3",
16
+ "mkdocs-material>=9.6.22",
17
+ "mkdocs-simple-hooks>=0.1.5",
18
+ "mkdocstrings>=0.30.1",
19
+ "mkdocstrings-python>=1.18.2",
20
+ "polars>=1.33.1",
21
+ "ruff>=0.14.1",
22
+ "rolling @ git+https://github.com/OutSquareCapital/rolling.git@add-type-stubs",
23
+ "cytoolz-stubs",
24
+ ]
25
+
26
+ [tool.ruff.format]
27
+ docstring-code-format = true
28
+
29
+ [tool.uv.sources]
30
+ cytoolz-stubs = { git = "https://github.com/OutSquareCapital/cytoolz-stubs.git" }
31
+ doctester = { git = "https://github.com/OutSquareCapital/doctester.git" }
32
+
33
+ [build-system]
34
+ build-backend = "uv_build"
35
+ requires = ["uv_build>=0.8.15,<0.9.0"]
@@ -0,0 +1,5 @@
1
+ from ._core import Wrapper
2
+ from ._dict import Dict
3
+ from ._iter import Iter, Seq
4
+
5
+ __all__ = ["Dict", "Iter", "Wrapper", "Seq"]
@@ -0,0 +1,23 @@
1
+ from ._format import Peeked, peek, peekn
2
+ from ._main import CommonBase, IterWrapper, MappingWrapper, Pipeable, Wrapper
3
+ from ._protocols import (
4
+ SizedIterable,
5
+ SupportsAllComparisons,
6
+ SupportsKeysAndGetItem,
7
+ SupportsRichComparison,
8
+ )
9
+
10
+ __all__ = [
11
+ "MappingWrapper",
12
+ "CommonBase",
13
+ "IterWrapper",
14
+ "Wrapper",
15
+ "SupportsAllComparisons",
16
+ "SupportsRichComparison",
17
+ "SupportsKeysAndGetItem",
18
+ "Peeked",
19
+ "SizedIterable",
20
+ "Pipeable",
21
+ "peek",
22
+ "peekn",
23
+ ]
@@ -0,0 +1,34 @@
1
+ from collections.abc import Iterable, Iterator, Mapping
2
+ from pprint import pformat
3
+ from typing import Any, NamedTuple
4
+
5
+ import cytoolz as cz
6
+
7
+
8
+ class Peeked[T](NamedTuple):
9
+ value: T | tuple[T, ...]
10
+ sequence: Iterator[T]
11
+
12
+
13
+ def peekn[T](data: Iterable[T], n: int) -> Iterator[T]:
14
+ peeked = Peeked(*cz.itertoolz.peekn(n, data))
15
+ print(f"Peeked {n} values: {peeked.value}")
16
+ return peeked.sequence
17
+
18
+
19
+ def peek[T](data: Iterable[T]) -> Iterator[T]:
20
+ peeked = Peeked(*cz.itertoolz.peek(data))
21
+ print(f"Peeked value: {peeked.value}")
22
+ return peeked.sequence
23
+
24
+
25
+ def dict_repr(
26
+ v: Mapping[Any, Any],
27
+ max_items: int = 20,
28
+ depth: int = 3,
29
+ width: int = 80,
30
+ compact: bool = True,
31
+ ) -> str:
32
+ truncated = dict(list(v.items())[:max_items])
33
+ suffix = "..." if len(v) > max_items else ""
34
+ return pformat(truncated, depth=depth, width=width, compact=compact) + suffix