In this lesson, you will learn how to gain granular control over how your custom objects are saved and loaded using the pickle module by defining __getstate__ and __setstate__.
Why Customize Serialization?
By default, Python’s pickle module saves an object's entire __dict__. However, sometimes you don't want to save everything. Perhaps your object contains a temporary network connection, a file handle, or a massive cache that shouldn't be serialized. The __getstate__ and __setstate__ methods allow you to intervene in this process.
Customizing the Process
__getstate__(self): This method is called automatically when youpickle.dump()an object. It should return a dictionary (or any data structure) that represents the "state" you want to save. If you want to exclude a specific attribute, simply omit it from this dictionary.__setstate__(self, state): This method is called duringpickle.load(). It receives the data you returned in__getstate__and allows you to restore your object’s attributes.
Practical Example
Imagine you have a Logger class that keeps a list of messages but also maintains a temporary, non-serializable file handle:
import pickle
class Logger:
def __init__(self, name):
self.name = name
self.messages = []
self.handle = open(f"{name}.log", "w") # File handles cannot be pickled
def __getstate__(self):
# Return only the data we want to save (excluding 'handle')
state = self.__dict__.copy()
del state['handle']
return state
def __setstate__(self, state):
# Restore the object and re-initialize the non-pickleable handle
self.__dict__.update(state)
self.handle = open(f"{self.name}.log", "a")
When you pickle this object, __getstate__ strips out the handle attribute so the process doesn't crash. When you unpickle it, __setstate__ restores the name and messages, and then manually re-opens the file so the object is ready for use again.
Key Takeaway: Use __getstate__ to define what data to save and __setstate__ to reconstruct your object’s internal state during unpickling.