How to Serialize Object in Python: Simple Guide
In Python, you can serialize an object using the
pickle module, which converts the object into a byte stream. Use pickle.dumps() to serialize to bytes or pickle.dump() to write directly to a file.Syntax
The pickle module provides two main functions for serialization:
pickle.dumps(obj): Convertsobjinto bytes.pickle.dump(obj, file): Writes the serializedobjdirectly to a file.
To deserialize, use pickle.loads(bytes) or pickle.load(file).
python
import pickle # Serialize object to bytes serialized_bytes = pickle.dumps(obj) # Serialize object to a file with open('file.pkl', 'wb') as f: pickle.dump(obj, f)
Example
This example shows how to serialize a Python dictionary to a file and then read it back (deserialize) to get the original object.
python
import pickle # Original object person = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'} # Serialize to file with open('person.pkl', 'wb') as file: pickle.dump(person, file) # Deserialize from file with open('person.pkl', 'rb') as file: loaded_person = pickle.load(file) print(loaded_person)
Output
{'name': 'Alice', 'age': 30, 'city': 'Wonderland'}
Common Pitfalls
Some common mistakes when serializing objects in Python include:
- Trying to serialize objects that are not supported by
pickle, like open file handles or database connections. - Forgetting to open files in binary mode (
'wb'for writing,'rb'for reading). - Not handling exceptions that may occur during serialization or deserialization.
Always ensure the object is pickleable and files are handled properly.
python
import pickle # Wrong: opening file in text mode person = {'name': 'Bob'} try: with open('person.txt', 'w') as f: pickle.dump(person, f) # This will raise an error except Exception as e: print('Error:', e) # Right: open file in binary mode with open('person.pkl', 'wb') as f: pickle.dump(person, f)
Output
Error: write() argument must be bytes, not str
Quick Reference
| Function | Purpose | Usage |
|---|---|---|
| pickle.dumps(obj) | Serialize object to bytes | bytes_data = pickle.dumps(obj) |
| pickle.dump(obj, file) | Serialize object to file | pickle.dump(obj, open('file.pkl', 'wb')) |
| pickle.loads(bytes) | Deserialize bytes to object | obj = pickle.loads(bytes_data) |
| pickle.load(file) | Deserialize object from file | obj = pickle.load(open('file.pkl', 'rb')) |
Key Takeaways
Use the pickle module to serialize and deserialize Python objects easily.
Always open files in binary mode when using pickle to avoid errors.
Not all Python objects can be serialized with pickle; avoid open files or connections.
Use pickle.dumps() for bytes and pickle.dump() for files.
Handle exceptions to make serialization robust.