Object cannot be pickled
Production Risk
CRITICAL security risk if unpickling untrusted data; use JSON or protobuf for untrusted serialization.
Raised when an object cannot be serialized by the pickle module — for example, lambda functions, open file handles, or database connections.
- 1Pickling a lambda function or local function
- 2Pickling an object that contains an open file handle or socket
- 3Pickling a thread.Lock or other OS-level resource
- 4Pickling a generator or coroutine
Pickling a lambda function.
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
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)
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.
import pickle pickle.dumps(lambda x: x) # AttributeError: can't pickle local object
import pickle
try:
data = pickle.dumps(obj)
except (pickle.PicklingError, AttributeError) as e:
print(f"Cannot pickle: {e}")import pickle def double(x): return x * 2 # module-level — picklable data = pickle.dumps(double)
✕ Unpickle data from untrusted sources
Pickle deserialization can execute arbitrary code; never unpickle data from untrusted sources.
Python Docs — pickle module
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev