0

I created a bit sequence custom type in C

typedef struct {
    PyObject_VAR_HEAD
    uint8_t data[1];
} BitStream;

static PyTypeObject BitStreamType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "my_module.BitStream",
    .tp_dealloc = 0,
    .tp_free = PyObject_Del,
    .tp_basicsize = offsetof(BitStream, data),
    .tp_itemsize = sizeof(uint8_t),
    .tp_flags = Py_TPFLAGS_DEFAULT,
};

I've tried pickling the result of some of my module's functions

with open(path, "wb") as outfile:
    pickle.dump(myobject, outfile)

but get the error

TypeError: cannot pickle 'my_module.BitStream' object

Looking around, I find that one can define .__reduce__() for their custom classes to let pickle pickle them.

The problem for me is, I'd prefer to store my custom class directly. I don't want to have to represent it using Python types (which is what it seems .__reduce__() is required to return)

What can I do to still allow it to be saved into and loaded from a binary file by pickle?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

0 Answers0