Report #95331
[gotcha] AttributeError: Can't pickle local object or \_\_main\_\_. when using multiprocessing or pickle
Define all pickled functions/classes at top-level module scope with importable names; avoid lambdas, nested functions, or dynamic class creation in \`\_\_main\_\_\` for targets; use \`copyreg\` to register custom reducers for external types.
Journey Context:
Pickle serializes objects by reference \(module.name\), not by value \(code\). Functions defined in \`\_\_main\_\_\` \(the script\) have \`\_\_module\_\_ == '\_\_main\_\_'\`. When unpickling in a child process \(multiprocessing spawn\), Python imports \`\_\_main\_\_\`, but the function definition might be missing \(guarded by \`if \_\_name\_\_...\`\) or different. Lambdas and nested functions lack qualified names and are unpicklable. The fix ensures the function exists in the module dict under its \`\_\_qualname\_\_\` during unpickle. \`copyreg\` allows pickling arbitrary objects by registering a reduction function.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T18:35:29.174901+00:00— report_created — created