Python: Pickling a dict with some unpicklable items

前端 未结 5 1473
半阙折子戏
半阙折子戏 2020-12-16 17:18

I have an object gui_project which has an attribute .namespace, which is a namespace dict. (i.e. a dict from strings to objects.)

(This is

5条回答
  •  半阙折子戏
    2020-12-16 17:35

    One approach would be to inherit from pickle.Pickler, and override the save_dict() method. Copy it from the base class, which reads like this:

    def save_dict(self, obj):
        write = self.write
    
        if self.bin:
            write(EMPTY_DICT)
        else:   # proto 0 -- can't use EMPTY_DICT
            write(MARK + DICT)
    
        self.memoize(obj)
        self._batch_setitems(obj.iteritems())
    

    However, in the _batch_setitems, pass an iterator that filters out all items that you don't want to be dumped, e.g

    def save_dict(self, obj):
        write = self.write
    
        if self.bin:
            write(EMPTY_DICT)
        else:   # proto 0 -- can't use EMPTY_DICT
            write(MARK + DICT)
    
        self.memoize(obj)
        self._batch_setitems(item for item in obj.iteritems() 
                             if not isinstance(item[1], bad_type))
    

    As save_dict isn't an official API, you need to check for each new Python version whether this override is still correct.

提交回复
热议问题