Pickle all attributes except one

后端 未结 6 1006
野性不改
野性不改 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 08:19

    I'd cut to the root of your problem, and try to serialize the so-called 'un-pickleable' items first. To do this, I'd use dill, which can serialize almost anything in python. Dill also has some good tools for helping you understand what is causing your pickling to fail when your code fails.

    >>> import dill
    >>> dill.loads(dill.dumps(your_bad_object))
    >>> ...
    >>> # if you get a pickling error, use dill's tools to figure out a workaround
    >>> dill.detect.badobjects(your_bad_object, depth=0)
    >>> dill.detect.badobjects(your_bad_object, depth=1)
    >>> ...
    

    If you absolutely wanted to, you could use dill's badobjects (or one of the other detection functions) to dive recursively into your object's reference chain, and pop out the unpickleable objects, instead of calling it at at every depth, as above.

提交回复
热议问题