Pickles the state of an object into a dictionary. The
dictionary is itself either saved as a pickled file (dump) or
pickled string (dumps). Alternatively, the dump_state method
will return the dictionary that is pickled.
The format of the state dict is quite strightfoward. Basic types
(bool, int, long, float, complex, None, string and unicode) are
represented as they are. Everything else is stored as a
dictionary containing metadata information on the object's type
etc. and also the actual object in the 'data' key. For example:
>>> p = StatePickler()
>>> p.dump_state(1)
1
>>> l = [1,2.0, None, [1,2,3]]
>>> p.dump_state(l)
{'data': [1, 2.0, None, {'data': [1, 2, 3], 'type': 'list', 'id': 1}],
'id': 0,
'type': 'list'}
Classes are also represented similarly. The state in this case is
obtained from the __getstate__ method or from the __dict__.
Here is an example:
>>> class A:
... __version__ = 1 # State version
... def __init__(self):
... self.attribute = 1
...
>>> a = A()
>>> p = StatePickler()
>>> p.dump_state(a)
{'class_name': 'A',
'data': {'data': {'attribute': 1}, 'type': 'dict', 'id': 2},
'id': 0,
'initargs': {'data': (), 'type': 'tuple', 'id': 1},
'module': '__main__',
'type': 'instance',
'version': [(('A', '__main__'), 1)]}
When pickling data, references are taken care of. Numeric arrays
can be pickled and are stored as a gzipped base64 encoded string.
© Copyright 2002-2009 Enthought, Inc.