1 """Helper to provide extensibility for pickle/cPickle.
3 This is only useful to add pickle support for extension types defined in
4 C, not for instances of user-defined classes.
7 from types
import ClassType
as _ClassType
9 __all__
= ["pickle","constructor"]
12 safe_constructors
= {}
14 def pickle(ob_type
, pickle_function
, constructor_ob
=None):
15 if type(ob_type
) is _ClassType
:
16 raise TypeError("copy_reg is not intended for use with classes")
18 if not callable(pickle_function
):
19 raise TypeError("reduction functions must be callable")
20 dispatch_table
[ob_type
] = pickle_function
22 if constructor_ob
is not None:
23 constructor(constructor_ob
)
25 def constructor(object):
26 if not callable(object):
27 raise TypeError("constructors must be callable")
28 safe_constructors
[object] = 1
30 # Example: provide pickling support for complex numbers.
32 def pickle_complex(c
):
33 return complex, (c
.real
, c
.imag
)
35 pickle(type(1j
), pickle_complex
, complex)
37 # Support for picking new-style objects
39 def _reconstructor(cls
, base
, state
):
40 obj
= base
.__new
__(cls
, state
)
41 base
.__init
__(obj
, state
)
43 _reconstructor
.__safe
_for
_unpickling
__ = 1
48 for base
in self
.__class
__.__mro
__:
49 if hasattr(base
, '__flags__') and not base
.__flags
__ & _HEAPTYPE
:
52 base
= object # not really reachable
57 args
= (self
.__class
__, base
, state
)
59 getstate
= self
.__getstate
__
60 except AttributeError:
63 except AttributeError:
68 return _reconstructor
, args
, dict
70 return _reconstructor
, args