Why must arguments and return values in `multiprocessing` code be picklable, and what commonly fails this requirement?
Answer
Because each worker process has entirely separate memory from the parent, `multiprocessing` cannot share Python objects directly across the process boundary; instead it serializes (pickles) the target function, its arguments, and its return value to send them between processes, and deserializes them on the other side. Common things that fail to pickle include lambdas, locally-defined nested functions and classes, open file handles, database connections, and unpicklable third-party objects like some GUI or driver handles — these need to be replaced with module-level functions/classes or re-created inside the worker process instead of being passed in directly.
Strong answer includes
- separate process memory means objects must be serialized across the boundary
- multiprocessing pickles the function, arguments, and return value
- lambdas, local functions/classes, open handles commonly fail to pickle
Practical example
pool.map(lambda x: x * 2, data)raises a `PicklingError` under `multiprocessing` , while replacing the lambda with a module-level
def double(x): return x * 2works correctly.