def to_bundle(self, prefix=''): """ Turns an object into a serialized bundle. Args: prefix: The prefix to prepend to the keys corresponding to the instance variable names Returns: A serialized bundle that can be unbundled into the same object. """ bnd = Bundle() metacount = 0 bnd.set_value(prefix + '.type', self.__class__.__name__) for key, val in self.__dict__.iteritems(): if isinstance(val, Bundleable): # take care of nested bundleables bnd.assimilate(val.to_bundle(prefix='%s.%s' % (prefix, key))) arg_type = val.__module__ + '.' + val.__class__.__name__ meta = BundleableMetadata(key, arg_type, '%s.%s' % (prefix, key)) bnd.assimilate( meta.to_bundle('%s.meta.%d' % (prefix, metacount))) metacount += 1 elif isinstance(val, list): # take care of a list if val: if isinstance(val[0], Bundleable): # list of bundleables bnd.assimilate( self.encode_list(val, prefix='%s.%s' % (prefix, key))) arg_type = val[0].__module__ + '.' + val[ 0].__class__.__name__ meta = ListMetadata(key, arg_type, '%s.%s' % (prefix, key), len(val)) bnd.assimilate( meta.to_bundle('%s.meta.%d' % (prefix, metacount))) metacount += 1 else: # list of primitives - anything that can be converted to/from a string for i, obj in enumerate(val): bnd.set_value('%s.%s.%d' % (prefix, key, i), obj) #TODO the line below only works if val is not empty meta = ListMetadata( key, 'prim.' + str(type(val[0]).__name__), '%s.%s' % (prefix, key), len(val)) bnd.assimilate( meta.to_bundle('%s.meta.%d' % (prefix, metacount))) metacount += 1 else: # empty list bnd.set_value('%s.%s' % (prefix, key), val) else: bnd.set_value(prefix + "." + key, self.__dict__[key]) return bnd
def encode_list(item_list, prefix=''): bnd = Bundle() for i, item in enumerate(item_list): bnd.assimilate(item.to_bundle('%s.%d' % (prefix, i))) return bnd