How do I serialize python objects that contain proto objects in them?

Viewed 184

Let's say I have a python class like so:

import pickle
import msg_pkt_pb2

class Solver(object):
  def __init__(self, proto_objs:msg_pkt_pb2.MessagePackets, _obj_fn=lambda x,y:(x - y)**2):
    self._proto_objs = proto_objs
    self.num_iterations = 0
    self.num_pass = 0
    self._obj_fn = _obj_fn
  
  def solve_or_die(self):
    try:
      ...
      _obj_fn(a, b)
    except:
      self._make_ckpt()

  def _make_ckpt(self):
    f = open('ckpt.pkl', 'wb')
    pickle.dump(self, f)
    f.close()
  
  def load_from_ckpt(self, filename):
    ...

Proto:

message MessagePkt {
   string name=1;
   int32 id=2;
   string payload=3;
}

message MessagePackets{
   int32 id=1;
   repeated MessagePacket message_pkts=2;
}

I want to serialize this object which contains a proto object(partially filled), unfortunately, when I try to serialize this object I get an exception:


_pickle.PicklingError: Can't pickle <class 'msg_pkt_pb2.MessagePackets'>: it's not the same object as msg_pkt_pb2.MessagePackets

Let me know what is the best way to save this object and load it back?

0 Answers
Related