Skip to content Skip to sidebar Skip to footer

How To Load A Pickle Object And Resolve Certain References

Say we have an object we write to binary file using pickle. Let's say the object graph looks like this: foo1 +--->bar | \--->context +--->baz | +--->context

Solution 1:

If the .context is of type Context, instead of setting context to None, you could adapt the code from the section Persistence of External Objects in the pickle documentation:

import pickle

class ContextAwarePickler(pickle.Pickler):
    def persistent_id(self, obj):
        # if this is a context, return the key
        if isinstance(obj, Context):
            return ("Context", context.key)

        # pickle as usual
        return None


class ContextAwareUnpickler(pickle.Unpickler):
    def recover_context(self, key_id):
        ...

    def persistent_load(self, pid):
        type_tag, key_id = pid
        if type_tag == "Context":
            return self.recover_context(key_id)
        else:
            raise pickle.UnpicklingError("unsupported persistent object")

Post a Comment for "How To Load A Pickle Object And Resolve Certain References"