Pickle all attributes except one

后端 未结 6 937
野性不改
野性不改 2021-01-17 07:51

What is the best way to write a __getstate__ method that pickles almost all of an object\'s attributes, but excludes a few?

I have an object wi

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 07:55

    The only alternative I can think of is some kind of helper function that iterates through an object's properties and adds them (or not) to the dictionary, based on the type.

    Yeah, I think that's pretty much what you're left with, if you want enough "magic" to allow yourself to be lazy (and/or allow for dynamically added attributes). Keep in mind that "pickle can't handle this" isn't the only reason you might not want to include something in the pickled state.

    But it's not as hard as you seem to think, assuming you have code for the "should I pickle this?" logic:

    def __getstate__(self):
      return dict((k, v) for (k, v) in self.__dict__.iteritems() if should_pickle(v))
    

提交回复
热议问题