pickle.PicklingError
PythonERRORNotableRuntime ErrorHIGH confidence

Object cannot be pickled

Production Risk

CRITICAL security risk if unpickling untrusted data; use JSON or protobuf for untrusted serialization.

What this means

Raised when an object cannot be serialized by the pickle module — for example, lambda functions, open file handles, or database connections.

Why it happens
  1. 1Pickling a lambda function or local function
  2. 2Pickling an object that contains an open file handle or socket
  3. 3Pickling a thread.Lock or other OS-level resource
  4. 4Pickling a generator or coroutine
How to reproduce

Pickling a lambda function.

trigger — this will error
trigger — this will error
import pickle
f = lambda x: x * 2
pickle.dumps(f)

expected output

AttributeError: Can't pickle local object '<lambda>'

Fix 1

Use a named function instead of lambda

WHEN Needing to pickle a callable

Use a named function instead of lambda
import pickle

def double(x):
    return x * 2

# Named module-level functions can be pickled
data = pickle.dumps(double)

Why this works

Pickle serializes functions by reference (module + qualname); module-level named functions work, lambdas and local functions do not.

Fix 2

Use cloudpickle for extended pickling support

WHEN Working with multiprocessing or distributed computing (Dask, Ray)

Use cloudpickle for extended pickling support
import cloudpickle

f = lambda x: x * 2
data = cloudpickle.dumps(f)  # Works with lambdas
result = cloudpickle.loads(data)(10)

Why this works

cloudpickle serializes the function bytecode directly, not just a reference.

Code examples
Triggerpython
import pickle
pickle.dumps(lambda x: x)  # AttributeError: can't pickle local object
Handle with try/exceptpython
import pickle
try:
    data = pickle.dumps(obj)
except (pickle.PicklingError, AttributeError) as e:
    print(f"Cannot pickle: {e}")
Avoid with named functionspython
import pickle

def double(x): return x * 2  # module-level — picklable

data = pickle.dumps(double)
What not to do

Unpickle data from untrusted sources

Pickle deserialization can execute arbitrary code; never unpickle data from untrusted sources.

Same error in other languages
Sources
Official documentation ↗

Python Docs — pickle module

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors