Why This Happens
Python's multiprocessing uses pickle to serialize objects between processes. Pickle cannot serialize lambdas, local functions, or closures. Only module-level functions work.
The Problem
from multiprocessing import Pool
def main():
func = lambda x: x ** 2
with Pool(4) as p:
results = p.map(func, range(10))The Fix
from multiprocessing import Pool
def square(x):
return x ** 2
def main():
with Pool(4) as p:
results = p.map(square, range(10))Step-by-Step Fix
- 1
Move functions to module level
Define at top level, not inside another function.
- 2
Replace lambdas
Convert to named functions at module level.
- 3
Use ThreadPoolExecutor
Threads do not require pickling and work with lambdas.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free