Skip to content Skip to sidebar Skip to footer

How To Create A Persistant Class Using Pickle In Python

New to python... I have the following class Key, that extends dict: class Key( dict ): def __init__( self ): self = { some dictionary stuff... } def __getstate__(

Solution 1:

I wrote a subclass of dict that does this here it is.

classAttrDict(dict):
    """A dictionary with attribute-style access. It maps attribute access to
    the real dictionary.  """def__init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)

    def__getstate__(self):
        return self.__dict__.items()

    def__setstate__(self, items):
        for key, val in items:
            self.__dict__[key] = val

    def__repr__(self):
        return"%s(%s)" % (self.__class__.__name__, dict.__repr__(self))

    def__setitem__(self, key, value):
        returnsuper(AttrDict, self).__setitem__(key, value)

    def__getitem__(self, name):
        returnsuper(AttrDict, self).__getitem__(name)

    def__delitem__(self, name):
        returnsuper(AttrDict, self).__delitem__(name)

    __getattr__ = __getitem__
    __setattr__ = __setitem__

    defcopy(self):
        return AttrDict(self)

It basically converts the state to a basic tuple, and takes that back again to unpickle.

But be aware that you have to have to original source file available to unpickle. The pickling does not actually save the class itself, only the instance state. Python will need the original class definition to re-create from.

Post a Comment for "How To Create A Persistant Class Using Pickle In Python"