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.65 KB | None | 0 0
  1. import pickle
  2.  
  3. class Parent:
  4. def __init__(self, serializable_data, third_party_object):
  5. self.serializable_data = serializable_data
  6. self.third_party_object = third_party_object # Could contain non-serializable parts
  7.  
  8. def __getstate__(self):
  9. state = {}
  10. for key, value in self.__dict__.items():
  11. try:
  12. # Try serializing the attribute
  13. pickle.dumps(value)
  14. state[key] = value
  15. except (pickle.PicklingError, TypeError):
  16. # If it's not serializable, exclude it
  17. print(f"Skipping non-serializable attribute: {key}")
  18. pass
  19. return state
  20.  
  21. def __setstate__(self, state):
  22. self.__dict__.update(state)
  23. # Optionally reinitialize any non-serializable attributes if necessary
  24. # (e.g., third_party_object could be reinitialized here)
  25.  
  26. # Example third-party object class
  27. class ThirdPartyObject:
  28. def __init__(self):
  29. self.serializable_part = "This is serializable"
  30. self.non_serializable_part = open("file.txt", "w") # This is not serializable
  31.  
  32. # Create an instance
  33. third_party_instance = ThirdPartyObject()
  34. parent_instance = Parent(serializable_data="Serializable data", third_party_object=third_party_instance)
  35.  
  36. # Pickle the parent object (non-serializable attributes will be skipped automatically)
  37. pickled_data = pickle.dumps(parent_instance)
  38.  
  39. # Unpickle the parent object
  40. unpickled_obj = pickle.loads(pickled_data)
  41.  
  42. print(unpickled_obj.serializable_data) # Will be restored
  43. print(unpickled_obj.third_party_object) # This may be None or partially restored
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement