Pickle all attributes except one

后端 未结 6 936
野性不改
野性不改 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:59

    For the your specific case (preventing a function from getting pickled), use this:

    self.__class__.fn = self.__class__.my_func

    Now, instead of adding a function to an instance of a class, you've added it to the class itself, thus the function won't get pickled. This won't work if you want each instance to have its own version of fn.

    My scenario was that I wanted to selectively add get_absolute_url to some Django models, and I wanted to define this in an abstract BaseModel class. I had self.get_absolute_url = … and ran into the pickle issue. Just added __class__ to the assignment solved the issue in my case.

提交回复
热议问题