PicklingError: Cannot Pickle Lambda or Local Function

AttributeError: Can't pickle local object

Quick Answer

Multiprocessing needs to serialize functions to send to workers, but lambdas and local functions cannot be pickled. Define functions at module level.

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. 1

    Move functions to module level

    Define at top level, not inside another function.

  2. 2

    Replace lambdas

    Convert to named functions at module level.

  3. 3

    Use ThreadPoolExecutor

    Threads do not require pickling and work with lambdas.

Bugsly 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