Can I mark variables as transient so they won't be pickled?

前端 未结 2 1408
甜味超标
甜味超标 2020-12-30 04:09

Let\'s say I have a class:

class Thing(object):
    cachedBar = None

    def __init__(self, foo):
        self.foo = foo

    def bar(self):
        if not          


        
相关标签:
2条回答
  • 2020-12-30 05:13

    Implement __getstate__ to return only what parts of an object to be pickled

    0 讨论(0)
  • 2020-12-30 05:14

    According to the Pickle documentation, you can provide a method called __getstate__(), which returns something representing the state you want to have pickled (if it isn't provided, pickle uses thing.__dict__). So, you can do something like this:

    class Thing:
          def __getstate__(self):
                state = dict(self.__dict__)
                del state['cachedBar']
                return state
    

    This doesn't have to be a dict, but if it is something else, you need to also implement __setstate__(state).

    0 讨论(0)
提交回复
热议问题