Trace one file step by step, then run the batch and test it
Before you run the batch, trace one file by hand.
files = [
[" Disk OK ", "", "disk ok", "Fan: ERROR"],
["Boot", None, "boot"],
[" ", "temp: error", "Temp: Error "],
]
The first file, step by step:
| After | Lines |
|---|---|
| start | [' Disk OK ', '', 'disk ok', 'Fan: ERROR'] |
("strip",) | ['Disk OK', '', 'disk ok', 'Fan: ERROR'] |
("lower",) | ['disk ok', '', 'disk ok', 'fan: error'] |
("drop_blank",) | ['disk ok', 'disk ok', 'fan: error'] |
("dedupe",) | ['disk ok', 'fan: error'] |
clean_all(files, recipe) returned [['disk ok', 'fan: error'], AttributeError("'NoneType' object has no attribute 'strip'"), ['temp: error']]. The second file has a line that isn't text, so its slot holds the error, and the third file is cleaned anyway.
The recipe [("strip",), ("lowercase",)] raised ValueError: bad step: ('lowercase',) before any file ran. So did ("replace", "error"), one argument short. files[0] was unchanged afterwards.
Test it with what this lesson's checkpoints test:
- a file that fails in the middle of the batch
- a bad recipe with a spy step in front of it
- results in order, with the first file held back
- a barrier to prove the files overlap
On these files, threads tied the loop and processes lost, so say so
Eight files of 20,000 lines each, about 4.8 MB of text, made by [[f" Host-{f} Event {i % 3000} error code {i % 7} " if i % 9 else "" for i in range(20_000)] for f in range(8)]. The recipe was [("strip",), ("lower",), ("replace", "error", "ERROR"), ("drop_blank",), ("dedupe",)]. Median of 3:
| Run | Time |
|---|---|
| a plain loop | 0.030 s |
| 4 threads | 0.030 s |
| 4 processes | 0.094 s |
The string methods run under the GIL, so threads don't help. The whole job costs less than starting the processes and pickling the lines.
Say so: here the loop wins. Threads earn their place only once the files come off slow storage, where each worker spends its time waiting.
For a process version, one has to move to the top level with the recipe as an argument: pool.map(clean_one, files, [recipe] * len(files)). A function defined inside clean_all can't be pickled. The lambdas in TRANSFORMS are fine either way: they never travel, because the worker imports them with the module.
A file too big for one worker splits into bands of lines, but dedupe needs the whole file
strip, lower, replace and drop_blank look at one line at a time, so they can run on bands. dedupe can't: a line in band 3 may repeat one in band 1. So it runs on the stitched whole, or it merges each band's first-seen lines in band order.
In the editor, write that merge, merge_firsts(bands). Each band already holds its own first-seen lines, and you return the first copy of each line across all bands, in band order.