17. Pickling C Extension Types¶
If you need to provide support for pickling your specialised types from your C extension then you need to implement some special functions.
This example shows you how to provided pickle support for for the custom2.Custom type described in the C extension
tutorial in the
Python documentation.
This defines an CustomObject object that has three fields; a first name, a last name and a number.
The CustomObject definition that needs to be pickled and un-pickled looks like this in C:
typedef struct {
PyObject_HEAD
PyObject *first; /* first name */
PyObject *last; /* last name */
int number;
} CustomObject;
The example C code is in
src/cpy/Pickle/cCustomPickle.c.The test code is in
tests/unit/test_c_custom_pickle.py.
17.1. Pickle Version Control¶
Since the whole point of pickle is persistence then pickled objects can hang around in databases, file systems,
data from the shelve module and whatnot for a long
time.
It is entirely possible that when un-pickled, sometime in the future, that your C extension has moved on and then
things become awkward.
It is strongly recommended that you add some form of version control to your pickled objects. In this example I just have a single integer version number which I write to the pickled object. If the number does not match on unpickling then I raise an exception. When I change the type API I would, judiciously, change this version number.
Clearly more sophisticated strategies are possible by supporting older versions of the pickled object in some way but this will do for now.
We add some simple pickle version information to the C extension:
static const char* PICKLE_VERSION_KEY = "_pickle_version";
static int PICKLE_VERSION = 1;
Now we can implement __getstate__ and __setstate__, think of these as symmetric operations.
First __getstate__.
17.2. Implementing __getstate__¶
__getstate__ pickles the object.
__getstate__ is expected to return a dictionary of the internal state of the Custom object.
Note that a Custom object has two Python objects (first and last) and a C integer (number) that need to
be converted to a Python object.
We also need to add the version information.
Here is the C implementation:
1/* Pickle the object */
2static PyObject *
3Custom___getstate__(CustomObject *self, PyObject *Py_UNUSED(ignored)) {
4 PyObject *ret = Py_BuildValue("{sOsOsisi}",
5 "first", self->first,
6 "last", self->last,
7 "number", self->number,
8 PICKLE_VERSION_KEY, PICKLE_VERSION);
9 return ret;
10}
Note
Note the careful use of Py_BuildValue().
"s" and "i" causes a new PyObject to be created in the dict.
"O" increments the reference count of an existing PyObject which is inserted into the dict.
17.3. Implementing __setstate__¶
The implementation of __setstate__ un-pickles the object.
This is a little more complicated as there is quite a lot of error checking going on.
We are being passed an arbitrary Python object and need to check:
It is a Python dictionary.
It has a version key and the version value is one that we can deal with.
It has the required keys and values to populate our
Customobject.
Note that our __new__ method (Custom_new()) has already been called on self.
Before setting any member value we need to de-allocate the existing value set by Custom_new() otherwise we will have a memory leak.
17.3.1. Error Checking¶
1/* Un-pickle the object */
2static PyObject *
3Custom___setstate__(CustomObject *self, PyObject *state) {
4 /* Error check. */
5 if (!PyDict_CheckExact(state)) {
6 PyErr_SetString(PyExc_ValueError, "Pickled object is not a dict.");
7 return NULL;
8 }
9 /* Version check. */
10 /* Borrowed reference but no need to increment as we create a C long
11 * from it. */
12 PyObject *temp = PyDict_GetItemString(state, PICKLE_VERSION_KEY);
13 if (temp == NULL) {
14 /* PyDict_GetItemString does not set any error state so we have to. */
15 PyErr_Format(PyExc_KeyError, "No \"%s\" in pickled dict.",
16 PICKLE_VERSION_KEY);
17 return NULL;
18 }
19 if (!PyLong_Check(temp)) {
20 PyErr_Format(
21 PyExc_KeyError,
22 "Pickled dict version key \"%s\" is not a long but type \"%s\".",
23 PICKLE_VERSION_KEY,
24 temp->ob_type->tp_name
25 );
26 return NULL;
27 }
28 int pickle_version = (int) PyLong_AsLong(temp);
29 if (pickle_version != PICKLE_VERSION) {
30 PyErr_Format(PyExc_ValueError,
31 "Pickle version mismatch. Got version %d but expected version %d.",
32 pickle_version, PICKLE_VERSION);
33 return NULL;
34 }
17.3.2. Set the first Member¶
1/* NOTE: Custom_new() will have been invoked so self->first and self->last
2 * will have been allocated so we have to de-allocate them. */
3temp = PyDict_GetItemString(state, "first"); /* Borrowed reference. */
4if (temp == NULL) {
5 /* PyDict_GetItemString does not set any error state so we have to. */
6 PyErr_SetString(PyExc_KeyError, "No \"first\" in pickled dict.");
7 return NULL;
8}
9if (!PyUnicode_Check(temp)) {
10 PyErr_Format(
11 PyExc_KeyError,
12 "Pickled dict key \"first\" is not a str but type \"%s\".",
13 temp->ob_type->tp_name
14 );
15 return NULL;
16}
17Py_DECREF(self->first);
18self->first = temp;
19Py_INCREF(self->first);
17.3.3. Set the last Member¶
This code is very similar to the code for the first member above.
1temp = PyDict_GetItemString(state, "last"); /* Borrowed reference. */
2if (temp == NULL) {
3 /* PyDict_GetItemString does not set any error state so we have to. */
4 PyErr_SetString(PyExc_KeyError, "No \"last\" in pickled dict.");
5 return NULL;
6}
7if (!PyUnicode_Check(temp)) {
8 PyErr_Format(
9 PyExc_KeyError,
10 "Pickled dict key \"last\" is not a str but type \"%s\".",
11 temp->ob_type->tp_name
12 );
13 return NULL;
14}
15Py_DECREF(self->last);
16self->last = temp;
17Py_INCREF(self->last);
17.3.4. Set the number Member¶
This is a C fundamental type so the code is slightly different:
1/* Borrowed reference but no need to incref as we create a C long from it. */
2PyObject *number = PyDict_GetItemString(state, "number");
3if (number == NULL) {
4 /* PyDict_GetItemString does not set any error state so we have to. */
5 PyErr_SetString(PyExc_KeyError, "No \"number\" in pickled dict.");
6 return NULL;
7}
8if (!PyLong_Check(number)) {
9 PyErr_Format(
10 PyExc_KeyError,
11 "Pickled dict key \"number\" is not an int but type \"%s\".",
12 number->ob_type->tp_name
13 );
14 return NULL;
15}
16self->number = (int) PyLong_AsLong(number);
And we are done.
Py_RETURN_NONE;
}
17.3.5. __setstate__ in Full¶
1static PyObject *
2Custom___setstate__(CustomObject *self, PyObject *state) {
3
4 if (!PyDict_CheckExact(state)) {
5 PyErr_SetString(PyExc_ValueError, "Pickled object is not a dict.");
6 return NULL;
7 }
8 /* Version check. */
9 /* Borrowed reference but no need to increment as we create a C long from it. */
10 PyObject *temp = PyDict_GetItemString(state, PICKLE_VERSION_KEY);
11 if (temp == NULL) {
12 /* PyDict_GetItemString does not set any error state so we have to. */
13 PyErr_Format(PyExc_KeyError, "No \"%s\" in pickled dict.", PICKLE_VERSION_KEY);
14 return NULL;
15 }
16 if (!PyLong_Check(temp)) {
17 PyErr_Format(
18 PyExc_KeyError,
19 "Pickled dict version key \"%s\" is not a long but type \"%s\".",
20 PICKLE_VERSION_KEY,
21 temp->ob_type->tp_name
22 );
23 return NULL;
24 }
25 int pickle_version = (int) PyLong_AsLong(temp);
26 if (pickle_version != PICKLE_VERSION) {
27 PyErr_Format(
28 PyExc_ValueError,
29 "Pickle version mismatch. Got version %d but expected version %d.",
30 pickle_version, PICKLE_VERSION
31 );
32 return NULL;
33 }
34
35 temp = PyDict_GetItemString(state, "first"); /* Borrowed reference. */
36 if (temp == NULL) {
37 /* PyDict_GetItemString does not set any error state so we have to. */
38 PyErr_SetString(PyExc_KeyError, "No \"first\" in pickled dict.");
39 return NULL;
40 }
41 if (!PyUnicode_Check(temp)) {
42 PyErr_Format(
43 PyExc_KeyError,
44 "Pickled dict key \"first\" is not a str but type \"%s\".",
45 temp->ob_type->tp_name
46 );
47 return NULL;
48 }
49 Py_DECREF(self->first);
50 self->first = temp;
51 Py_INCREF(self->first);
52
53 temp = PyDict_GetItemString(state, "last"); /* Borrowed reference. */
54 if (temp == NULL) {
55 /* PyDict_GetItemString does not set any error state so we have to. */
56 PyErr_SetString(PyExc_KeyError, "No \"last\" in pickled dict.");
57 return NULL;
58 }
59 if (!PyUnicode_Check(temp)) {
60 PyErr_Format(
61 PyExc_KeyError,
62 "Pickled dict key \"last\" is not a str but type \"%s\".",
63 temp->ob_type->tp_name
64 );
65 return NULL;
66 }
67 Py_DECREF(self->last);
68 self->last = temp;
69 Py_INCREF(self->last);
70
71 /* Borrowed reference but no need to increment as we create a C long from it. */
72 PyObject *number = PyDict_GetItemString(state, "number");
73 if (number == NULL) {
74 /* PyDict_GetItemString does not set any error state so we have to. */
75 PyErr_SetString(PyExc_KeyError, "No \"number\" in pickled dict.");
76 return NULL;
77 }
78 if (!PyLong_Check(number)) {
79 PyErr_Format(
80 PyExc_KeyError,
81 "Pickled dict key \"number\" is not an int but type \"%s\".",
82 number->ob_type->tp_name
83 );
84 return NULL;
85 }
86 self->number = (int) PyLong_AsLong(number);
87
88 Py_RETURN_NONE;
89}
17.4. Add the Special Methods¶
Now we need to add these two special methods to the methods table which now looks like this:
1static PyMethodDef Custom_methods[] = {
2 /* Existing methods here... */
3 {"__getstate__", (PyCFunction) Custom___getstate__, METH_NOARGS,
4 "Pickle the Custom object"
5 },
6 {"__setstate__", (PyCFunction) Custom___setstate__, METH_O,
7 "Un-pickle the Custom object"
8 },
9 {NULL} /* Sentinel */
10};
17.5. Pickling a custom2.Custom Object¶
We can test this with code like this that pickles one custom2.Custom object then creates another custom2.Custom
object from that pickle.
Here is some Python code that exercises our module (tests are in tests/unit/test_c_custom_pickle.py):
1import io
2import pickle
3import pickletools
4import sys
5
6import pytest
7
8from cPyExtPatt import cPickle
9
10
11def test_module_dir():
12 assert dir(cPickle) == [
13 'Custom', '__doc__', '__file__', '__loader__',
14 '__name__', '__package__', '__spec__',
15 ]
16
17
18ARGS_FOR_CUSTOM_CLASS = ('FIRST', 'LAST', 11)
19PICKLE_BYTES_FOR_CUSTOM_CLASS = (
20 b'\x80\x04\x95f\x00\x00\x00\x00\x00\x00\x00\x8c\x12cPyExtPatt.cPickle\x94'
21 b'\x8c\x06Custom\x94\x93\x94)\x81\x94}\x94(\x8c\x05first\x94\x8c\x05FIRST'
22 b'\x94\x8c\x04last\x94\x8c\x04LAST\x94\x8c\x06number\x94K\x0b\x8c\x0f_pickle_'
23 b'version\x94K\x01ub.'
24)
25
26def test_pickle_getstate():
27 custom = cPickle.Custom(*ARGS_FOR_CUSTOM_CLASS)
28 pickled_value = pickle.dumps(custom)
29 print()
30 print(f'Pickled original is {pickled_value}')
31 assert pickled_value == PICKLE_BYTES_FOR_CUSTOM_CLASS
32 # result = pickle.loads(pickled_value)
33
34
35def test_pickle_setstate():
36 custom = pickle.loads(PICKLE_BYTES_FOR_CUSTOM_CLASS)
37 assert custom.first == 'FIRST'
38 assert custom.last == 'LAST'
39 assert custom.number == 11
40
41def test_pickle_round_trip():
42 custom = cPickle.Custom(*ARGS_FOR_CUSTOM_CLASS)
43 pickled_value = pickle.dumps(custom)
44 result = pickle.loads(pickled_value)
45 assert id(result) != id(custom)
So we have pickled one object and recreated a different, but equivalent, instance from the pickle of the original object which is what we set out to do.
17.6. The Pickled Object in Detail¶
If you are curious about the contents of the pickled object the the Python standard library provides the pickletools module. This allows you to inspect the pickled object. Here is a test for that:
1import io
2import pickle
3import pickletools
4import sys
5
6import pytest
7
8from cPyExtPatt import cPickle
9
10def test_pickletools():
11 outfile = io.StringIO()
12 pickletools.dis(PICKLE_BYTES_FOR_CUSTOM_CLASS, out=outfile, annotate=1)
13 result = outfile.getvalue()
14 expected = '<See below>'
15 assert result == expected
The expected output will be something like this:
1Pickled original is b'\x80\x04\x95[\x00\x00\x00\x00\x00\x00\x00\x8c\x07custom2\x94\x8c\x06Custom\x94\x93\x94)\x81\x94}\x94(\x8c\x05first\x94\x8c\x05FIRST\x94\x8c\x04last\x94\x8c\x04LAST\x94\x8c\x06number\x94K\x0b\x8c\x0f_pickle_version\x94K\x01ub.'
2 0: \x80 PROTO 4 Protocol version indicator.
3 2: \x95 FRAME 91 Indicate the beginning of a new frame.
4 11: \x8c SHORT_BINUNICODE 'custom2' Push a Python Unicode string object.
5 20: \x94 MEMOIZE (as 0) Store the stack top into the memo. The stack is not popped.
6 21: \x8c SHORT_BINUNICODE 'Custom' Push a Python Unicode string object.
7 29: \x94 MEMOIZE (as 1) Store the stack top into the memo. The stack is not popped.
8 30: \x93 STACK_GLOBAL Push a global object (module.attr) on the stack.
9 31: \x94 MEMOIZE (as 2) Store the stack top into the memo. The stack is not popped.
10 32: ) EMPTY_TUPLE Push an empty tuple.
11 33: \x81 NEWOBJ Build an object instance.
12 34: \x94 MEMOIZE (as 3) Store the stack top into the memo. The stack is not popped.
13 35: } EMPTY_DICT Push an empty dict.
14 36: \x94 MEMOIZE (as 4) Store the stack top into the memo. The stack is not popped.
15 37: ( MARK Push markobject onto the stack.
16 38: \x8c SHORT_BINUNICODE 'first' Push a Python Unicode string object.
17 45: \x94 MEMOIZE (as 5) Store the stack top into the memo. The stack is not popped.
18 46: \x8c SHORT_BINUNICODE 'FIRST' Push a Python Unicode string object.
19 53: \x94 MEMOIZE (as 6) Store the stack top into the memo. The stack is not popped.
20 54: \x8c SHORT_BINUNICODE 'last' Push a Python Unicode string object.
21 60: \x94 MEMOIZE (as 7) Store the stack top into the memo. The stack is not popped.
22 61: \x8c SHORT_BINUNICODE 'LAST' Push a Python Unicode string object.
23 67: \x94 MEMOIZE (as 8) Store the stack top into the memo. The stack is not popped.
24 68: \x8c SHORT_BINUNICODE 'number' Push a Python Unicode string object.
25 76: \x94 MEMOIZE (as 9) Store the stack top into the memo. The stack is not popped.
26 77: K BININT1 11 Push a one-byte unsigned integer.
27 79: \x8c SHORT_BINUNICODE '_pickle_version' Push a Python Unicode string object.
28 96: \x94 MEMOIZE (as 10) Store the stack top into the memo. The stack is not popped.
29 97: K BININT1 1 Push a one-byte unsigned integer.
30 99: u SETITEMS (MARK at 37) Add an arbitrary number of key+value pairs to an existing dict.
31 100: b BUILD Finish building an object, via __setstate__ or dict update.
32 101: . STOP Stop the unpickling machine.
33highest protocol among opcodes = 4
17.7. Pickling Objects with External State¶
This is just a simple example, if your object relies on external state such as open files, databases and the like you need to be careful, and knowledgeable about your state management. There is some useful information in Handling Stateful Objects
Note
Marshalling support for use with the marshall module is given by the C Marshall API
17.8. References¶
Python API documentation for __setstate__
Python API documentation for __getstate__
Useful documentation for Handling Stateful Objects
Python pickle module
Python shelve module