scout-rig 0.2.6 → 0.2.7

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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +31 -13
  3. data/README.md +27 -4
  4. data/Rakefile +1 -0
  5. data/VERSION +1 -1
  6. data/doc/Improvements.md +396 -0
  7. data/doc/StartHere.md +95 -0
  8. data/doc/developer/Architecture.md +232 -0
  9. data/doc/developer/DataConversionInternals.md +407 -0
  10. data/doc/developer/DesignPrinciples.md +254 -0
  11. data/doc/developer/PythonTaskRunnerInternals.md +371 -0
  12. data/doc/developer/PythonWorkflowInternals.md +539 -0
  13. data/doc/developer/ScoutPythonInternals.md +504 -0
  14. data/doc/user/Cookbook.md +337 -0
  15. data/doc/user/DefiningPythonTasks.md +708 -0
  16. data/doc/user/DrivingWorkflowsFromPython.md +418 -0
  17. data/doc/user/IteratingPythonData.md +142 -0
  18. data/doc/user/PassingDataToPython.md +223 -0
  19. data/doc/user/PythonEnvironments.md +197 -0
  20. data/doc/user/RunningPythonFromRuby.md +267 -0
  21. data/doc/user/ScriptingPython.md +281 -0
  22. data/doc/user/TestingAndPackaging.md +487 -0
  23. data/lib/scout/python/script.rb +11 -2
  24. data/lib/scout/workflow/python/inputs.rb +33 -23
  25. data/lib/scout/workflow/python/task.rb +219 -22
  26. data/lib/scout/workflow/python.rb +236 -9
  27. data/lib/scout-rig/testing/availability.rb +608 -0
  28. data/python/README.md +51 -0
  29. data/python/scout/__init__.py +2 -0
  30. data/python/scout/runner.py +193 -29
  31. data/python/scout/task_errors.py +6 -0
  32. data/research/00_scope_and_themes.md +131 -0
  33. data/research/data-conversion-and-scripting-analysis.md +209 -0
  34. data/research/design-philosophy-analysis.md +246 -0
  35. data/research/python-helper-package-analysis.md +272 -0
  36. data/research/pythonworkflow-analysis.md +199 -0
  37. data/research/scoutpython-bridge-analysis.md +185 -0
  38. data/research/synthesis-report.md +109 -0
  39. data/research/testing-availability-baseline.md +1625 -0
  40. data/research/testing-availability-final-report.md +500 -0
  41. data/research/validation-report.md +149 -0
  42. data/scout-rig.gemspec +35 -5
  43. data/test/scout/python/test_util.rb +13 -0
  44. data/test/scout/test_python.rb +10 -0
  45. data/test/scout/workflow/python/test_task.rb +1119 -1
  46. data/test/scout-rig/testing/test_availability.rb +495 -0
  47. data/test/scout-rig/testing/test_test_support.rb +166 -0
  48. data/test/test_helper.rb +96 -19
  49. metadata +47 -4
  50. data/doc/Python.md +0 -482
  51. data/doc/PythonWorkflow.md +0 -163
@@ -0,0 +1,418 @@
1
+ # Driving Workflows from Python
2
+
3
+ This document explains how to use the Python `scout` package to run Scout
4
+ workflows from Python code, both locally (via the Ruby CLI) and remotely
5
+ (via HTTP).
6
+
7
+ ## Audience
8
+
9
+ This page is intended for:
10
+
11
+ - ✓ Python developers who want to use Scout workflows
12
+ - ✓ Agent developers building Python-side workflow clients
13
+ - ✗ Framework contributors
14
+
15
+ ## When to use this
16
+
17
+ Use the Python `scout` package when:
18
+
19
+ - You're working primarily in Python and need to call Scout workflows.
20
+ - You want to drive Scout workflows from a Jupyter notebook.
21
+ - You're building a Python application that uses Scout for computation.
22
+ - You need to interact with a remote Scout workflow server over HTTP.
23
+
24
+ ## Core concepts
25
+
26
+ The Python `scout` package is a **thin CLI wrapper**. It does not embed the
27
+ Ruby runtime — it shells out to the Scout CLI (`rbbt` / `rbbt_exec.rb`) for
28
+ all operations. This means:
29
+
30
+ - You need Scout and Rbbt installed and available on your PATH.
31
+ - The package is not a replacement for the Ruby stack.
32
+ - Performance is bounded by CLI process startup time.
33
+
34
+ Every Ruby call the package makes is a fresh subprocess: `scout.cmd()` runs
35
+ `rbbt_exec.rb` with the Ruby source on stdin, and `run_job()` runs
36
+ `rbbt workflow task ...`. There is no persistent Ruby process, so a
37
+ `Workflow` object is pure state — `wf.tasks()` and `wf.task_info()` shell out
38
+ each time they are called.
39
+
40
+ Both `numpy` and `pandas` are imported at module import time, so
41
+ `import scout` fails if either is missing; the two are hard requirements of
42
+ the local package, not conveniences.
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install "scout-rig @ git+https://github.com/mikisvaz/scout-rig.git@main#subdirectory=python"
48
+ ```
49
+
50
+ With remote workflow support:
51
+
52
+ ```bash
53
+ pip install "scout-rig[remote] @ git+https://github.com/mikisvaz/scout-rig.git@main#subdirectory=python"
54
+ ```
55
+
56
+ Requirements:
57
+ - Python >= 3.10
58
+ - numpy, pandas (imported at `import scout` time; hard requirements)
59
+ - `requests` (for remote workflows — see the caveat under
60
+ "Remote workflow execution")
61
+ - Scout/Rbbt Ruby stack installed and on PATH, specifically the
62
+ `rbbt_exec.rb` and `rbbt` commands
63
+
64
+ ## Local workflow execution
65
+
66
+ ### List tasks
67
+
68
+ ```python
69
+ import scout
70
+ import scout.workflow as sw
71
+
72
+ wf = sw.Workflow('Baking')
73
+ print(wf.tasks())
74
+ # ['bake_muffin_tray', 'prepare_batter', 'whisk_eggs', 'bake_blueberry_muffin_tray']
75
+ ```
76
+
77
+ `tasks()` shells out once and splits stdout on newlines, so it reflects the
78
+ workflow as currently installed. Requiring a workflow that is not installed
79
+ triggers Scout's auto-install (a `git clone` of the workflow's repository
80
+ under `~/.rbbt/workflows/`) on the first call — verified with `Baking`,
81
+ which was cloned from `https://github.com/Rbbt-Workflows/Baking.git` and
82
+ then listed normally. If the repository cannot be resolved the Ruby side
83
+ raises `Workflow repo does not exist: <url>` and `tasks()` surfaces that
84
+ text as the return value, since `cmd()` ignores the exit status.
85
+
86
+ Note the naming convention the lookup uses: the workflow *class* `Baking` maps
87
+ to the lowercase repository `baking`. In this environment `rbbt workflow task
88
+ Baking bake_muffin_tray` failed to resolve
89
+ `https://github.com/Scout-Workflows/baking.git` (no such repo) even though
90
+ `rbbt_exec.rb` and `Workflow.require_workflow` had installed
91
+ `Rbbt-Workflows/Baking` — i.e. the two entry points consult different repo
92
+ lists. Metadata calls (`tasks()`, `task_info()`) worked; actually *running*
93
+ `Baking` jobs did not. If `wf.run()` raises
94
+ `RuntimeError: Workflow repo does not exist: ...`, check which repository your
95
+ `rbbt` resolves the workflow name to before blaming the Python layer.
96
+
97
+ ### Get task information
98
+
99
+ ```python
100
+ info = wf.task_info('bake_muffin_tray')
101
+ print(info)
102
+ ```
103
+
104
+ `task_info` returns the **raw JSON string** produced by the Ruby side, not a
105
+ parsed dict — call `json.loads(info)` yourself if you need the fields. The
106
+ keys observed for the `Baking` example are `id`, `description`, `inputs`,
107
+ `input_types`, `input_defaults`, `input_descriptions`, `input_options`,
108
+ `input_use`, `returns`, `dependencies`, `extension`; a task with no declared
109
+ return type has `"returns": null`.
110
+
111
+ ### Run a task (synchronous)
112
+
113
+ ```python
114
+ result = wf.run('bake_muffin_tray', add_blueberries=True)
115
+ print(result)
116
+ ```
117
+
118
+ `run` returns the **stripped stdout** of the underlying
119
+ `rbbt workflow task` invocation. That is the task's log/progress output
120
+ first and the final result last; for multi-line output you normally want the
121
+ last line. On a non-zero exit it raises `RuntimeError` carrying the
122
+ command's stderr (or stdout when stderr is empty).
123
+
124
+ (Verified at the `run_job` level in this environment — the flags, the temp
125
+ input directory, the `RuntimeError` on failure and the stripped-stdout return
126
+ were all observed with a local workflow. The exact shape of a successful
127
+ `Baking` result line was **not** observed, because this checkout could not
128
+ resolve that workflow's repository; treat the "log then result" description
129
+ as Scout CLI behaviour, not something probed here.)
130
+
131
+ ### Run a task asynchronously
132
+
133
+ ```python
134
+ # Fork the job (runs in background)
135
+ step = wf.fork('bake_muffin_tray', add_blueberries=True)
136
+
137
+ # Poll for completion
138
+ step.join() # Blocks until done, error, or aborted
139
+
140
+ # Get the result
141
+ data = step.load()
142
+ print(data)
143
+ ```
144
+
145
+ `fork` passes `--fork --detach`, so the Ruby CLI returns as soon as the job
146
+ is issued; `Step` then re-shells out once per poll. `step.path` is the job
147
+ directory path printed by the CLI, and every accessor on `Step`
148
+ (`info`, `status`, `load`) invokes `rbbt_exec.rb` again.
149
+
150
+ Note the polling granularity: `join()` sleeps a fixed **1 second** between
151
+ checks with **no timeout**, and `Step.info()` only reads the job's `.info`
152
+ file — a path that was never issued (or was cleaned) yields an empty dict,
153
+ and `status()` then raises `KeyError: 'status'`. Treat `Step.info()` as
154
+ "the info Scout currently has on disk", not a guaranteed schema.
155
+
156
+ ## Reading Scout TSV files
157
+
158
+ The `scout` package provides helpers for reading Scout-style TSV files
159
+ directly into pandas DataFrames:
160
+
161
+ ```python
162
+ import scout
163
+
164
+ df = scout.tsv('data.tsv')
165
+ print(df.head())
166
+ ```
167
+
168
+ The reader handles Scout TSV conventions:
169
+ - Preamble lines (`#:type=:list#:sep=:`) are parsed into metadata.
170
+ - Header lines (`#Key\tField1\tField2`) become column names.
171
+ - The key field becomes the DataFrame index.
172
+
173
+ Verified behaviour of `tsv()` / `tsv_pandas()` worth knowing before you rely
174
+ on it:
175
+
176
+ - `#:type=:flat` files are read with `header=None, skiprows=[0,1]` and the
177
+ preamble's own `sep` if it declares one, so the whole body becomes the
178
+ index of a zero-column DataFrame.
179
+ - A file whose first line is a plain `#name` header (no preamble, no field
180
+ header) is read as a **flat single-column** frame: the label becomes the
181
+ index name and there are no data columns (verified).
182
+ - A `#:type=:list` file with **no** field header is likewise read flat: the
183
+ preamble is consumed and the body becomes a zero-column index. A list file
184
+ that *does* carry a `#Key<TAB>Field` header line falls into the generic
185
+ branch instead, and `header=start` then consumes the first data row as
186
+ the pandas header — a four-row body yields a three-row frame whose first
187
+ body row becomes the column labels (verified: `#K\tF` header over
188
+ `x\ty / 1\t2 / 3\t4` gives one column literally named `y` and rows
189
+ `x` and `1`). This looks like a bug rather than a design decision.
190
+ - A file with **no** `#` header at all (`fields: None`, `type: "list"`) is
191
+ passed to `read_table` with `index_col=0` and no column names, which
192
+ raises `TypeError: Index(...) must be called with a collection ...`
193
+ in recent pandas. Header-less files are therefore not readable as-is.
194
+ - The reader only inspects the **first two** lines; a preamble without a
195
+ following field header is fine (`start` stays 1, `fields` absent).
196
+ - Extra `**kwargs` go straight to `pandas.read_table`; passing `header=`
197
+ yourself conflicts with the internally computed one and raises
198
+ `TypeError: ... got multiple values for keyword argument 'header'`.
199
+
200
+ `save_tsv(filename, df, key=None)` writes `#<key>\t<cols>\n...`. The key
201
+ label defaults to the DataFrame's `index.name`, then to `"Key"`, and an
202
+ explicit `key=` overrides both.
203
+
204
+ ### Writing Scout TSV files
205
+
206
+ ```python
207
+ import scout
208
+ import pandas as pd
209
+
210
+ df = pd.DataFrame({'Gene': ['BRCA1', 'TP53'], 'Score': [1.2, 3.4]})
211
+ df = df.set_index('Gene')
212
+ scout.save_tsv('output.tsv', df)
213
+ ```
214
+
215
+ ## Remote workflow execution
216
+
217
+ For interacting with Scout REST workflow servers:
218
+
219
+ ```python
220
+ # NOTE: `from scout.workflow.remote import RemoteWorkflow` does NOT work at
221
+ # HEAD — see the caveats below this example. Load the module by file path:
222
+ import importlib.util
223
+ spec = importlib.util.spec_from_file_location(
224
+ 'scout.workflow.remote', 'python/scout/workflow/remote.py')
225
+ remote = importlib.util.module_from_spec(spec)
226
+ spec.loader.exec_module(remote)
227
+
228
+ wf = remote.RemoteWorkflow('http://localhost:1900/Baking')
229
+ print(wf.tasks)
230
+
231
+ # Run a job
232
+ step = wf.job('bake_muffin_tray', add_blueberries=True)
233
+
234
+ # Poll
235
+ step.wait()
236
+
237
+ # Get result
238
+ print(step.json())
239
+ ```
240
+
241
+ Two caveats before you use this module:
242
+
243
+ - **`requests` is imported at module level**, so importing
244
+ `scout.workflow.remote` without `requests` installed raises
245
+ `ModuleNotFoundError: No module named 'requests'`. The `[remote]` pip
246
+ extra installs the dependency but does not make the import optional.
247
+ - **There is no `scout/workflow/__init__.py`.** `scout.workflow` is the
248
+ module `scout/workflow.py`, and Python resolves that *module* before it
249
+ would consider the `scout/workflow/` directory a package, so
250
+ `from scout.workflow.remote import ...` fails with
251
+ `ModuleNotFoundError: No module named 'scout.workflow.remote';
252
+ 'scout.workflow' is not a package` on Python 3.12/3.13 (verified). The
253
+ remote client is currently unreachable through the normal import path;
254
+ load it with `importlib.util.spec_from_file_location` if you need it.
255
+
256
+ Note also that `RemoteWorkflow` exposes the task list as the attribute
257
+ `wf.tasks` (a plain list, not a method) — the code above prints it
258
+ directly. Constructing a `RemoteWorkflow` immediately GETs the workflow URL
259
+ and expects the JSON export shape `{"asynchronous": [...],
260
+ "synchronous": [...], "exec": [...]}`.
261
+
262
+ ### RemoteStep methods
263
+
264
+ | Method | Description |
265
+ |--------|-------------|
266
+ | `info()` | Get job info as JSON |
267
+ | `status()` | Get job status string |
268
+ | `done()` | Check if done |
269
+ | `error()` | Check if errored (`error` **or** `aborted`) |
270
+ | `running()` | Check if currently running |
271
+ | `wait(time=1)` | Poll `status()` every `time` seconds until done/error |
272
+ | `raw()` | Get result as raw bytes |
273
+ | `json()` | Get result as JSON |
274
+
275
+ Failure behaviour (verified against a stub server):
276
+
277
+ - Any HTTP status other than 200 makes `get_json`/`get_raw` log
278
+ `ERROR:root:Failed to initialize remote tasks` and return `None`; callers
279
+ that subscript the result then fail with `TypeError` on `None`. Nothing
280
+ raises a typed error on its own.
281
+ - A connection that cannot be established propagates `requests`'
282
+ `ConnectionError` directly (the constructor does not catch it).
283
+ - `wait()` has **no timeout**: a job whose status never leaves `running`
284
+ polls forever. Polling is a plain `sleep`-based loop with no backoff.
285
+ - `job(task, **kwargs)` POSTs with `_format=jobname`; on success the jobname
286
+ is used to build the step URL `url/task/jobname`.
287
+ - `task_info(name)` builds its URL as `join(self.url, name, '/info')`, and
288
+ `join` is a plain string concat with `/`, so the requested path is
289
+ `<url>/<name>//info` (a double slash — verified against a stub server).
290
+ The local `Workflow.task_info` (no slash) is the reliable one.
291
+
292
+ ## How inputs are passed
293
+
294
+ When you call `wf.run('task', param=value)`, the Python package:
295
+
296
+ 1. Materializes each input value to a file in a temp directory
297
+ (via `save_job_inputs`).
298
+ 2. Passes the temp directory to Scout via `--load_inputs`.
299
+ 3. Scout reads the files and matches them to task inputs.
300
+
301
+ Input types are mapped to file formats (file name = input name, extension
302
+ appended):
303
+
304
+ | Python type | File name | Content |
305
+ |-------------|-----------|---------|
306
+ | `str` | `<name>.txt` | raw string |
307
+ | `bool` | `<name>` | `true` or `false` |
308
+ | `int`/`float` | `<name>` | decimal string |
309
+ | `pandas.DataFrame` | `<name>.tsv` | Scout-style TSV via `save_tsv` |
310
+ | `list`/`ndarray` | `<name>.list` | newline-separated |
311
+
312
+ Verified details:
313
+
314
+ - `list` / `ndarray` values are joined with `"
315
+ ".join(value)`, so they must
316
+ contain **strings**; a numpy integer array raises
317
+ `TypeError: sequence item 0: expected str instance, numpy.int64 found`.
318
+ Convert with `.astype(str)` first.
319
+ - Any other type raises
320
+ `TypeError: Unsupported data type for argument '<name>': <type>`.
321
+ - The temp directory is removed immediately after the subprocess returns
322
+ (including on the error path), so the input files are not inspectable
323
+ afterwards.
324
+ - Keyword arguments other than the documented ones
325
+ (`jobname`, `fork`, `clean`, `exec`) are all treated as job inputs and
326
+ materialized; there is no validation against the task's declared inputs.
327
+ - `clean=True` adds `--clean`, `clean='recursive'` adds `--recursive_clean`;
328
+ `exec=True` adds `--exec`; `fork=True` adds `--fork --detach`. Note that
329
+ `exec` shadows the builtin inside `run_job` — that is the parameter's
330
+ actual name.
331
+
332
+ ## Command-line interaction
333
+
334
+ The `scout.cmd()` function is the foundation of the Python package. It
335
+ executes Ruby code via `rbbt_exec.rb`:
336
+
337
+ ```python
338
+ import scout
339
+
340
+ # Run arbitrary Ruby via the Scout CLI
341
+ result = scout.cmd('puts Time.now')
342
+ print(result)
343
+ ```
344
+
345
+ This is useful for quick introspection or when the higher-level wrappers
346
+ don't cover your use case.
347
+
348
+ Verified details of `cmd()`:
349
+
350
+ - The Ruby source is passed on **stdin** (`input=cmd.encode('utf-8')`) and
351
+ only stdout is returned, decoded as text. **stderr is discarded** — a Ruby
352
+ exception surfaces as a `#:rbbt_exec Error` marker on *stdout* followed by
353
+ the backtrace, not as a Python exception, and the exit status is ignored.
354
+ - `rbbt_exec.rb` must be on `PATH`; otherwise `subprocess.run` raises
355
+ `FileNotFoundError: [Errno 2] No such file or directory: 'rbbt_exec.rb'`.
356
+ - `cmd(None)` prints the literal string `Rbbt` and returns `None` (an
357
+ easter egg / status ping rather than an error).
358
+ - `libdir()` is `cmd('puts Rbbt.find(:lib)').rstrip()`: it resolves through
359
+ Scout's path lookup, so it returns the Scout **library root** of whatever
360
+ environment `rbbt_exec.rb` picks up — from a checkout of this repository
361
+ that is the checkout itself (trailing `/` included), and from an unrelated
362
+ directory it can degrade to `/` when nothing matches.
363
+ - `scout.path(subdir)` resolves `lib` then `base` (`~/.rbbt`) and returns
364
+ the first existing; `scout.read()` opens the resolved path and raises
365
+ plain `FileNotFoundError` when nothing exists.
366
+
367
+ ## Common mistakes
368
+
369
+ ### Scout not on PATH
370
+
371
+ The Python package shells out to `rbbt` and `rbbt_exec.rb`. If these
372
+ commands aren't on your PATH, you'll get `FileNotFoundError`. Ensure the
373
+ Ruby Scout stack is installed.
374
+
375
+ ### Confusing `run` and `fork`
376
+
377
+ `run()` is synchronous — it blocks until the job completes and returns the
378
+ result. `fork()` is asynchronous — it starts the job in the background and
379
+ returns a `Step` you can poll.
380
+
381
+ ### Printing to stdout in Python tasks
382
+
383
+ When running a Python task via the CLI, the function's return value is
384
+ printed to stdout. If your function also prints to stdout, the output will
385
+ be corrupted. Use `sys.stderr` for debug output.
386
+
387
+ ### Assuming `run()` returns only the result
388
+
389
+ `run()` returns the whole stripped stdout of
390
+ `rbbt workflow task`, which includes Scout's progress log lines. Parse the
391
+ last line, or write the result to a file and read it back, when a task logs
392
+ while it runs.
393
+
394
+ ### Assuming `Step.info()` always has a `status`
395
+
396
+ `Step.info()` parses the job's `.info` file. For a path with no info file
397
+ (the job was never issued under that name, or was cleaned) Ruby returns an
398
+ empty object, and `status()` raises `KeyError: 'status'` (verified with a
399
+ path that was never issued). `load()` on the same path fails later, with
400
+ `json.JSONDecodeError`, because Ruby prints nothing for an empty `.load`.
401
+ Guard on `info().get('status')` instead.
402
+
403
+ ### Expecting remote errors to raise
404
+
405
+ `scout.workflow.remote` logs HTTP failures through `logging.error` and
406
+ returns `None`. Configure the `logging` module if you want to see those
407
+ messages, and check for `None` before subscripting.
408
+
409
+ ## See also
410
+
411
+ - [Defining Python Tasks](DefiningPythonTasks.md) — Writing Python-backed
412
+ Scout tasks, including the `scout.task` docstring format.
413
+ - [Python Task Runner Internals](../developer/PythonTaskRunnerInternals.md)
414
+ — The exact docstring grammar `describe_function` parses, the generated
415
+ CLI's serialization rules, and its exit codes.
416
+ - [Passing Data to Python](PassingDataToPython.md) — Data conversion between
417
+ Ruby and Python.
418
+ - [Cookbook](Cookbook.md) — Recipes for common patterns.
@@ -0,0 +1,142 @@
1
+ # Iterating Python Data
2
+
3
+ This document explains how to traverse Python iterables from Ruby using
4
+ the iteration helpers provided by ScoutPython.
5
+
6
+ ## Audience
7
+
8
+ This page is intended for:
9
+
10
+ - ✓ Workflow authors processing Python data structures from Ruby
11
+ - ✓ Agent developers iterating over Python collections
12
+ - ✗ Framework contributors
13
+
14
+ ## When to use this
15
+
16
+ Use the iteration helpers when:
17
+
18
+ - A Python function returns a list, iterator, or generator that you need
19
+ to process in Ruby.
20
+ - You want to collect Python data into Ruby arrays.
21
+ - You need to iterate over a large Python dataset with a progress bar.
22
+
23
+ ## Core concepts
24
+
25
+ PyCall wraps Python objects in Ruby proxies. To traverse them, you need
26
+ special helpers because Ruby's native `each` doesn't work directly on
27
+ PyCall-wrapped iterables.
28
+
29
+ ScoutPython provides three helpers:
30
+
31
+ | Helper | Returns | When to use |
32
+ |--------|---------|-------------|
33
+ | `iterate` | Yields each element | General purpose: lists, iterators, generators |
34
+ | `iterate_index` | Yields each element | Indexable sequences (lists, tuples) |
35
+ | `collect` | Ruby Array | When you need all elements in an array |
36
+
37
+ Iteration ends when Python raises `StopIteration`; that exception is
38
+ handled internally and never reaches your block. Any *other* Python
39
+ exception raised during iteration propagates to Ruby as a
40
+ `PyCall::PyError`, and the progress bar (if any) is marked as errored.
41
+
42
+ `iterate` is **lazy**: each element is pulled from Python only when the
43
+ block asks for it, so an infinite or very large generator is not
44
+ materialized up front. Break out of the block when you have enough
45
+ elements (the Python side sees its next `__next__` never arrive).
46
+
47
+ ## Typical usage
48
+
49
+ ### iterate
50
+
51
+ `iterate` handles both `__iter__`/`__next__` style iterators and indexable
52
+ sequences. It first tries the iterator protocol, then falls back to
53
+ index-based access.
54
+
55
+ ```ruby
56
+ ScoutPython.run :numpy, as: :np do
57
+ arr = np.array([10, 20, 30])
58
+
59
+ ScoutPython.iterate(arr) do |elem|
60
+ puts elem # 10, 20, 30
61
+ end
62
+ end
63
+ ```
64
+
65
+ ### iterate with a progress bar
66
+
67
+ ```ruby
68
+ ScoutPython.run :numpy, as: :np do
69
+ arr = np.arange(1000)
70
+
71
+ ScoutPython.iterate(arr, bar: "Processing array") do |elem|
72
+ # Process each element
73
+ end
74
+ end
75
+ ```
76
+
77
+ Use `bar: true` for a default progress bar, or `bar: "Description"` for a
78
+ custom label. The progress bar uses Scout's `Log::ProgressBar`.
79
+
80
+ ### iterate_index
81
+
82
+ For indexable sequences (where `len()` and `[]` work), `iterate_index`
83
+ uses index-based access:
84
+
85
+ ```ruby
86
+ ScoutPython.run do
87
+ pyimport :json
88
+ data = json.loads('[{"name": "Alice"}, {"name": "Bob"}]')
89
+
90
+ ScoutPython.iterate_index(data) do |elem|
91
+ puts elem["name"]
92
+ end
93
+ end
94
+ ```
95
+
96
+ ### collect
97
+
98
+ `collect` gathers all elements into a Ruby array:
99
+
100
+ ```ruby
101
+ ScoutPython.run :numpy, as: :np do
102
+ arr = np.array([10, 20, 30])
103
+ result = ScoutPython.collect(arr)
104
+ puts result.inspect # [10, 20, 30]
105
+ end
106
+ ```
107
+
108
+ ## Common mistakes
109
+
110
+ ### Using `each` on PyCall objects
111
+
112
+ Ruby's `each` doesn't work on PyCall-wrapped iterables:
113
+
114
+ ```ruby
115
+ # Bad — will fail or produce unexpected results
116
+ ScoutPython.run do
117
+ pyimport :json
118
+ data = json.loads('[1, 2, 3]')
119
+ data.each { |x| puts x } # TypeError or no-op
120
+ end
121
+ ```
122
+
123
+ ### Using `iterate` on dictionaries
124
+
125
+ `iterate` is for sequences and iterators. For dictionaries, use `obj2hash`
126
+ or `dict2hash` to convert to a Ruby hash first:
127
+
128
+ ```ruby
129
+ # Bad — iterate on a dict doesn't do what you'd expect
130
+ ScoutPython.iterate(my_dict) { |k| ... }
131
+
132
+ # Good
133
+ hash = ScoutPython.obj2hash(my_dict)
134
+ hash.each { |k, v| ... }
135
+ ```
136
+
137
+ ## See also
138
+
139
+ - [Running Python from Ruby](RunningPythonFromRuby.md) — Execution modes.
140
+ - [Passing Data to Python](PassingDataToPython.md) — Data conversion helpers.
141
+ - [Logging and Progress](https://github.com/mikisvaz/scout-essentials/blob/main/doc/user/LoggingAndProgress.md)
142
+ in scout-essentials — The `Log::ProgressBar` used for iteration progress bars.