Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement pickle in python binding #245

Open
yannrichet opened this issue Jan 9, 2023 · 1 comment
Open

implement pickle in python binding #245

yannrichet opened this issue Jan 9, 2023 · 1 comment

Comments

@yannrichet
Copy link
Member

yannrichet commented Jan 9, 2023

needed for python frontend like dataiku, which stores python model using pickle...
pybind11 should provide most of api :

py::class_<Archive>(m, "Archive")
    .def(py::pickle(
        [](const Archive& a) { // dump
            return py::make_tuple(a.member1, a.member2, a.member3);
        },
        [](py::tuple t) { // load
            return Archive{t[0].cast<T>(), t[1].cast<T>(), t[2].cast<T>()};
        }
    ));
@yannrichet
Copy link
Member Author

more details in https://pybind11.readthedocs.io/en/stable/advanced/classes.html

py::class_<Pickleable>(m, "Pickleable")
    .def(py::init<std::string>())
    .def("value", &Pickleable::value)
    .def("extra", &Pickleable::extra)
    .def("setExtra", &Pickleable::setExtra)
    .def(py::pickle(
        [](const Pickleable &p) { // __getstate__
            /* Return a tuple that fully encodes the state of the object */
            return py::make_tuple(p.value(), p.extra());
        },
        [](py::tuple t) { // __setstate__
            if (t.size() != 2)
                throw std::runtime_error("Invalid state!");

            /* Create a new C++ instance */
            Pickleable p(t[0].cast<std::string>());

            /* Assign any additional state */
            p.setExtra(t[1].cast<int>());

            return p;
        }
    ));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant