3/34
Part 1 of 8 · StepsLearn and do
Write each step as a name and its arguments, not as a function
You could write the cleanup as a list of functions:
cleanup = [
lambda t: clip(t, 0, 40),
lambda t: sort_by(t, 1),
lambda t: scale(t, 10),
lambda t: head(t, 2),
]
Or as a list of steps, where each step is a tuple of a name and its arguments:
cleanup = [("clip", 0, 40), ("sort", 1), ("scale", 10), ("head", 2)]
Both give [[250, 0, 240], [210, 190, 230]]. The difference is what you can do with the list without running it:
| With the list you want to | A list of functions | A list of steps |
|---|---|---|
| print it in a log | [<function <lambda> at 0x101a16ac0>, <function <lambda> at 0x1015ea2a0>, ...] | [('clip', 0, 40), ('sort', 1), ('scale', 10), ('head', 2)] |
| check it before running | the arguments are hidden inside closures | every name and argument is right there |
| save it as JSON | TypeError: Object of type function is not JSON serializable | [["clip", 0, 40], ["sort", 1], ["scale", 10], ["head", 2]] |
| send it to another process | PicklingError: Can't pickle <function <lambda> at 0x101a16ac0>: attribute lookup <lambda> on __main__ failed | 63 bytes with pickle.dumps |
A step list is a value. You can compare two of them, store one with a job, show one to a user, and send one to a worker process. That last one decides the design of the parallel version, later in this lesson.
In the editor, use the step list cleanup as a value. Write describe(steps), one log line for a step list, and from_json(text), which reads a step list back from JSON and makes each step a tuple again.