First off I'm not expecting a solution, just hoping for some pointers on how to start.
I've got a C program with an embedded Python interpreter. The Python scripts the program uses as input obviously refer to the C-defined objects and functions. I'd now like to make some of these objects pickleable.
The pickle docs describe how extension types can be made picklable using __reduce__
. But this is a Python method - how would I define this in the underlying PyObject?
Fairly sure I'm mis-understanding something...
Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it's the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network.
Generally you can pickle any object if you can pickle every attribute of that object. Classes, functions, and methods cannot be pickled -- if you pickle an object, the object's class is not pickled, just a string that identifies what class it belongs to.
The pickle module can store things such as data types such as booleans, strings, and byte arrays, lists, dictionaries, functions, and more.
Once the file is opened for writing, you can use pickle. dump() , which takes two arguments: the object you want to pickle and the file to which the object has to be saved. In this case, the former will be dogs_dict , while the latter will be outfile . Don't forget to close the file with close() !
The pickle
module comes in both a python-only and a C variant (called cPickle
). As such, the __reduce__
method needs to be callable from Python code.
Thus, you need to provide a __reduce__
entry in your C object PyMethodDef
struct with a suitable implementation.
Alternatively, you can also register a pickling function with the copy_reg
module. This module's original usecase was to support extension modules better; the source code for the module states:
This is only useful to add pickle support for extension types defined in C, not for instances of user-defined classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With