A worked example: cleaning log files in parallel
Clarify the prompt, then say the design before the code
The prompt: you get log files, each a list of lines, and a recipe of cleanup steps such as [("strip",), ("lower",), ("drop_blank",), ("dedupe",)]. Return the cleaned files, in order. Run up to 4 files at a time. A file that can't be cleaned must not stop the others, and a recipe with a mistake in it should be rejected up front.
Clarify first, out loud:
- Which steps exist, and what arguments does each take?
- Does
dedupekeep the first copy of a line, and the order? Yes. - Should a failed file's slot hold the error, or be dropped? Hold the error, so the results line up with the files.
- May the input be changed? No.
- Are the files already in memory, or do they have to be read? In memory, for now.
Design, before code. The recipe is data: a name and its arguments per step. An ARITY dict checks it, and a TRANSFORMS dict runs it. Each file is independent, so the batch shape fits: check the recipe once, clean each file inside a try, and use pool.map for input order.
from concurrent.futures import ThreadPoolExecutor
ARITY = {"strip": 0, "lower": 0, "replace": 2, "drop_blank": 0, "dedupe": 0}
TRANSFORMS = {
"strip": lambda lines: [line.strip() for line in lines],
"lower": lambda lines: [line.lower() for line in lines],
"replace": lambda lines, old, new: [line.replace(old, new) for line in lines],
"drop_blank": lambda lines: [line for line in lines if line],
"dedupe": lambda lines: list(dict.fromkeys(lines)),
}
def check(recipe):
for step in recipe:
name, *args = step
if ARITY.get(name) != len(args) or not all(isinstance(arg, str) for arg in args):
raise ValueError(f"bad step: {step!r}")
def clean(lines, recipe):
lines = list(lines)
for name, *args in recipe:
lines = TRANSFORMS[name](lines, *args)
return lines
def clean_all(files, recipe, workers=4):
check(recipe)
def one(lines):
try:
return clean(lines, recipe)
except Exception as error:
return error
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(one, files))
Say two things while you write it. dedupe is dict.fromkeys, from the hash maps lesson: the first copy of each line, in order. And list(lines) is a full copy here, because a line is a string, and strings can't be changed in place. With tables, the rows were lists, and each needed its own copy.
In the editor, write two of the recipe's steps as plain functions: drop_blank(lines) and dedupe(lines).