Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pickle
- class Parent:
- def __init__(self, serializable_data, non_serializable_data):
- self.serializable_data = serializable_data
- self.non_serializable_data = non_serializable_data # For example, this could be an open file handle
- def __getstate__(self):
- # Return a dictionary with only the serializable attributes
- state = self.__dict__.copy()
- # Remove or modify non-serializable attributes
- if 'non_serializable_data' in state:
- state['non_serializable_data'] = None # Set to None or exclude it entirely
- return state
- def __setstate__(self, state):
- # Restore the object’s state from the pickle
- self.__dict__.update(state)
- # Restore or reinitialize the non-serializable attribute if necessary
- if self.non_serializable_data is None:
- self.non_serializable_data = "Reinitialized value"
- # Create an instance
- obj = Parent(serializable_data="This can be serialized", non_serializable_data=open("file.txt", "w"))
- # Pickle the object (non-serializable part will be skipped)
- pickled_data = pickle.dumps(obj)
- # Unpickle the object
- unpickled_obj = pickle.loads(pickled_data)
- print(unpickled_obj.serializable_data) # This will be restored
- print(unpickled_obj.non_serializable_data) # This would be None or reinitialized
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement