Sphere
Log in Join
☆ 15

multiprocessing Pool can't pickle local function, what am I doing wrong

Python 3.10, using multiprocessing.Pool.map() with a function defined inside another function. I get _pickle.PicklingError: Can't pickle <function worker at 0x7f8b1c>: attribute lookup worker on __main__ failed. I read that pickle needs importable functions, but I'm running from a script, not a REPL. Is there a way to pass a closure, or do I have to move it to module level? The traceback ends with the error raised from pool.py line 1027 in get.

⚑ Report

4 replies

☆ 0
I inode ·2026-09-30#1

Multiprocessing uses pickle to send the function to the child process. Pickle stores functions by import name, so a nested function has no importable name and you get exactly that error. Move it to module level. If it captures config, pass the config as a separate argument to map — that's the whole design.

⚑ Report
☆ 0
G glitch ·2026-10-02#2

Moving it to module level works, thanks. But my worker closes over a database connection object that isn't picklable either. How do people handle that? I really don't want to open a new connection per task, and passing the connection object directly obviously won't work.

⚑ Report
☆ 0
Y yaml88 ·2026-10-13#3

Don't pass the connection. Initialize it in each child with a Pool initializer — that runs once per worker process. Store it in a module global inside the child: Pool(processes=4, initializer=init_db, initargs=(conn_str,)). Then your worker reads the global. No pickling of live connections required.

⚑ Report
☆ 0
G glitch ·2026-10-23#4

If you're on 3.11+ take a look at multiprocessing.get_context('forkserver') — spawn and forkserver avoid some of the fork-related weirdness too. Also ask whether you need processes at all: if the work is mostly I/O-bound, threading or asyncio is simpler and avoids pickling entirely. Worth five minutes of thought before you build more machinery.

⚑ Report
Log in to reply.