Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pickle
- class Parent:
- def __init__(self, serializable_data, third_party_object):
- self.serializable_data = serializable_data
- self.third_party_object = third_party_object # Could contain non-serializable parts
- def __getstate__(self):
- state = {}
- for key, value in self.__dict__.items():
- try:
- # Try serializing the attribute
- pickle.dumps(value)
- state[key] = value
- except (pickle.PicklingError, TypeError):
- # If it's not serializable, exclude it
- print(f"Skipping non-serializable attribute: {key}")
- pass
- return state
- def __setstate__(self, state):
- self.__dict__.update(state)
- # Optionally reinitialize any non-serializable attributes if necessary
- # (e.g., third_party_object could be reinitialized here)
- # Example third-party object class
- class ThirdPartyObject:
- def __init__(self):
- self.serializable_part = "This is serializable"
- self.non_serializable_part = open("file.txt", "w") # This is not serializable
- # Create an instance
- third_party_instance = ThirdPartyObject()
- parent_instance = Parent(serializable_data="Serializable data", third_party_object=third_party_instance)
- # Pickle the parent object (non-serializable attributes will be skipped automatically)
- pickled_data = pickle.dumps(parent_instance)
- # Unpickle the parent object
- unpickled_obj = pickle.loads(pickled_data)
- print(unpickled_obj.serializable_data) # Will be restored
- print(unpickled_obj.third_party_object) # This may be None or partially restored
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement