Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 1 | """Helper to provide extensibility for pickle/cPickle. |
| 2 | |
| 3 | This is only useful to add pickle support for extension types defined in |
| 4 | C, not for instances of user-defined classes. |
| 5 | """ |
| 6 | |
| 7 | from types import ClassType as _ClassType |
Guido van Rossum | 72be306 | 1997-05-20 18:03:22 +0000 | [diff] [blame] | 8 | |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 9 | __all__ = ["pickle","constructor"] |
| 10 | |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 11 | dispatch_table = {} |
| 12 | safe_constructors = {} |
| 13 | |
Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 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") |
| 17 | |
| 18 | if not callable(pickle_function): |
| 19 | raise TypeError("reduction functions must be callable") |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 20 | dispatch_table[ob_type] = pickle_function |
| 21 | |
Guido van Rossum | 72be306 | 1997-05-20 18:03:22 +0000 | [diff] [blame] | 22 | if constructor_ob is not None: |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 23 | constructor(constructor_ob) |
| 24 | |
| 25 | def constructor(object): |
Fred Drake | 78a6a36 | 2000-10-11 22:16:45 +0000 | [diff] [blame] | 26 | if not callable(object): |
| 27 | raise TypeError("constructors must be callable") |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 28 | safe_constructors[object] = 1 |
| 29 | |
Guido van Rossum | 72be306 | 1997-05-20 18:03:22 +0000 | [diff] [blame] | 30 | # Example: provide pickling support for complex numbers. |
Guido van Rossum | 4706562 | 1997-04-09 17:44:11 +0000 | [diff] [blame] | 31 | |
Guido van Rossum | 72be306 | 1997-05-20 18:03:22 +0000 | [diff] [blame] | 32 | def pickle_complex(c): |
| 33 | return complex, (c.real, c.imag) |
| 34 | |
| 35 | pickle(type(1j), pickle_complex, complex) |