Advertisement
Guest User

Untitled

a guest
Sep 13th, 2024
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import pickle
  2.  
  3. class Parent:
  4. def __init__(self, serializable_data, non_serializable_data):
  5. self.serializable_data = serializable_data
  6. self.non_serializable_data = non_serializable_data # For example, this could be an open file handle
  7.  
  8. def __getstate__(self):
  9. # Return a dictionary with only the serializable attributes
  10. state = self.__dict__.copy()
  11. # Remove or modify non-serializable attributes
  12. if 'non_serializable_data' in state:
  13. state['non_serializable_data'] = None # Set to None or exclude it entirely
  14. return state
  15.  
  16. def __setstate__(self, state):
  17. # Restore the object’s state from the pickle
  18. self.__dict__.update(state)
  19. # Restore or reinitialize the non-serializable attribute if necessary
  20. if self.non_serializable_data is None:
  21. self.non_serializable_data = "Reinitialized value"
  22.  
  23. # Create an instance
  24. obj = Parent(serializable_data="This can be serialized", non_serializable_data=open("file.txt", "w"))
  25.  
  26. # Pickle the object (non-serializable part will be skipped)
  27. pickled_data = pickle.dumps(obj)
  28.  
  29. # Unpickle the object
  30. unpickled_obj = pickle.loads(pickled_data)
  31.  
  32. print(unpickled_obj.serializable_data) # This will be restored
  33. print(unpickled_obj.non_serializable_data) # This would be None or reinitialized
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement