16/34
Part 5 of 8 · Threads or processesLearn and do

A function can go to a process only if it is a top-level def

Pickle sends a function as its module and its name, and the worker imports it. So the pickle docs list only functions that can be reached from the top level of a module: built-in ones, and ones defined there with def, not lambda. Tried one at a time with pickle.dumps:

ObjectResult
[("clip", 0, 40), ("sort", 1), ("scale", 10), ("head", 2)]63 bytes
[("map", to_fahrenheit), ("head", 1)], with to_fahrenheit a top-level def in tables.py62 bytes: the names tables and to_fahrenheit, not the code
a lambdaPicklingError: Can't pickle <function <lambda> at 0x...>: attribute lookup <lambda> on __main__ failed
a function defined inside another functionAttributeError: Can't get local object 'make.<locals>.f'
threading.Lock()TypeError: cannot pickle '_thread.lock' object
a generatorTypeError: cannot pickle 'generator' object
an open fileTypeError: cannot pickle 'TextIOWrapper' instances

This is where steps as data pays off. The worker gets names and numbers, looks each name up in its own copy of TRANSFORMS, and runs it. A list of lambdas can't make the trip at all. Submitting apply(table, [("map", lambda v: v * 2)]) to a process pool raised _pickle.PicklingError from future.result(), while [("map", abs)] ran fine.

The same rule covers the function you hand the pool. A worker imports your main module, so the workers must be able to import it. Keep the work in top-level functions, and start the pool under if __name__ == "__main__":, as the script above does. Then importing the module doesn't start pools of its own.

That's also why this lesson's checkpoints use threads. They run your code from a string, which a worker process can't import.

In the editor, write can_send(obj): True when pickle.dumps(obj) works. The rows of the table above are your test cases, and the failures raise different exception types.