blob: e4f0b3cfdac0e83b44a20809de9ce9c1be21cc24 [file] [log] [blame]
Fred Drake78a6a362000-10-11 22:16:45 +00001"""Helper to provide extensibility for pickle/cPickle.
2
3This is only useful to add pickle support for extension types defined in
4C, not for instances of user-defined classes.
5"""
6
7from types import ClassType as _ClassType
Guido van Rossum72be3061997-05-20 18:03:22 +00008
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00009__all__ = ["pickle","constructor"]
10
Guido van Rossum47065621997-04-09 17:44:11 +000011dispatch_table = {}
12safe_constructors = {}
13
Fred Drake78a6a362000-10-11 22:16:45 +000014def 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")
17
18 if not callable(pickle_function):
19 raise TypeError("reduction functions must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000020 dispatch_table[ob_type] = pickle_function
21
Guido van Rossum72be3061997-05-20 18:03:22 +000022 if constructor_ob is not None:
Guido van Rossum47065621997-04-09 17:44:11 +000023 constructor(constructor_ob)
24
25def constructor(object):
Fred Drake78a6a362000-10-11 22:16:45 +000026 if not callable(object):
27 raise TypeError("constructors must be callable")
Guido van Rossum47065621997-04-09 17:44:11 +000028 safe_constructors[object] = 1
29
Guido van Rossum72be3061997-05-20 18:03:22 +000030# Example: provide pickling support for complex numbers.
Guido van Rossum47065621997-04-09 17:44:11 +000031
Guido van Rossum72be3061997-05-20 18:03:22 +000032def pickle_complex(c):
33 return complex, (c.real, c.imag)
34
35pickle(type(1j), pickle_complex, complex)