Pickle
In one line
pickle converts Python objects to bytes (and back) for saving to files or sending over networks.
In simple words
The pickle module serializes (pickles) almost any Python object into a byte stream, and deserializes (unpickles) it back. This lets you save objects to files, send them over networks, or cache them.
pickle.dumps(obj) returns bytes, pickle.loads(bytes) returns the object. File variants: pickle.dump(obj, file) and pickle.load(file).
Security warning: Never unpickle data from an untrusted source! Pickle can execute arbitrary code during unpickling, making it a major security risk. Use JSON for untrusted or cross-language data.
Pickle handles custom objects, but the class must be importable when unpickling.
Example
import pickle
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
# Serialize to bytes
data = pickle.dumps(p)
print(f"Pickled size: {len(data)} bytes")
# Deserialize back
p2 = pickle.loads(data)
print(f"Restored: {p2.name}, {p2.age}") # Alice, 30
print(p is p2) # False — new objectpickle.dumps converts any picklable object to bytes. pickle.loads reconstructs it. Never unpickle untrusted data!
Common confusions
Confused with: json
The difference: pickle can serialize almost any Python object (custom classes, functions, complex types) but produces Python-specific binary and is unsafe with untrusted data. json only handles basic types (dict, list, str, num, bool, null) but is safe, human-readable, and cross-language.
Related terms
Related Resources
Related Lessons
- Python Standard Library
pickle module.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.