How to stop attributes from being pickled in Python

Ries picture Ries · Jun 8, 2010 · Viewed 8.6k times · Source

I am using gnosis.xml.pickle to convert an object of my own class to xml. The object is initialized so that:

self.logger = MyLogger()

But when I do dump the object to a string I get an exception stating that the pickler encountered an unpickleable type (thread.lock).

Is there a way to 'tag' the logger attribute so that pickler will know not to try and pickle that attribute?

Answer

FogleBird picture FogleBird · Jun 8, 2010

You can define two methods, __getstate__ and __setstate__, to your class to override the default pickling behavior.

http://docs.python.org/library/pickle.html#object.__getstate__

__getstate__ should return a dict of attributes that you want to pickle.

def __getstate__(self):
    d = dict(self.__dict__)
    del d['logger']
    return d

__setstate__ should setup your object with the provided dict.

def __setstate__(self, d):
    self.__dict__.update(d) # I *think* this is a safe way to do it

Note that __init__ won't be called when unpickling so you'll have to create your logger in __setstate__