Conditional use of

So I have a class that remembers its instances based on an ID. When unpickling such an object there are two cases I'd like to handle:

  • No other instance with that ID exists, so a new instance is generated and __setstate__ should be called normally.
  • When another instance of that ID exists, that object is returned and I want to avoid calling __setstate__ on it.
  • Please take a look at this class definition.

    You will notice that currently I update only attributes that evaluate to False as a workaround.

    I can think of two general strategies to solve this:

  • As in this previous answer, I could define another function that is called with the result from __getnewargs__ and attach some attribute that tells me whether to run __setstate__ or not.
  • If I can tell whether the class' __call__ method was called from within pickle I could do the same.
  • I do not know if it's possible to further interfere with the pickling machinery and I don't want to subclass the unpickler.

    Thoughts, recommendations, completely different solutions? Thank you.

    链接地址: http://www.djcxy.com/p/64824.html

    上一篇: UnpicklingError:NEWOBJ类参数不是一个类型对象

    下一篇: 有条件地使用