Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1)
- import pickle
- class Parent:
- def __init__(self, serializable_data, third_party_object):
- self.serializable_data = serializable_data
- self.third_party_object = third_party_object # Object from third-party library
- def __getstate__(self):
- state = self.__dict__.copy()
- # Handle third-party object serialization
- if 'third_party_object' in state:
- try:
- # Attempt to pickle the third-party object (or specific parts of it)
- pickle.dumps(state['third_party_object'])
- except pickle.PicklingError:
- # If it fails, replace it with a placeholder or None
- state['third_party_object'] = None
- return state
- def __setstate__(self, state):
- self.__dict__.update(state)
- # Optionally reinitialize the third-party object if needed
- if self.third_party_object is None:
- self.third_party_object = "Reinitialize or set to a default value"
- # Example usage:
- 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
- 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 will be None or reinitialized
- 2)
- import pickle
- import weakref
- class Parent:
- def __init__(self, serializable_data, third_party_object):
- self.serializable_data = serializable_data
- # Store a weak reference to the third-party object if it's not serializable
- self.third_party_object = weakref.ref(third_party_object)
- def __getstate__(self):
- state = self.__dict__.copy()
- # We don't pickle weak references, so set it to None or leave it out
- state['third_party_object'] = None
- return state
- def __setstate__(self, state):
- self.__dict__.update(state)
- # Reinitialize or re-fetch the third-party object as necessary
- self.third_party_object = None
- # Example usage as above, but storing weak references
- 3)
- import copyreg
- # Define how to serialize/deserialize third-party objects
- def pickle_third_party_object(obj):
- # You can return just the serializable parts of the object
- return ThirdPartyObject, () # Returning constructor and arguments to re-create it
- # Register the function with copyreg
- copyreg.pickle(ThirdPartyObject, pickle_third_party_object)
- # Now when you pickle, the registered function will be used to handle ThirdPartyObject
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement