16 Pickleable(
const std::string &
value) : m_value(value) { }
17 const std::string &
value()
const {
return m_value; }
19 void setExtra1(
int extra1) { m_extra1 = extra1; }
20 void setExtra2(
int extra2) { m_extra2 = extra2; }
21 int extra1()
const {
return m_extra1; }
22 int extra2()
const {
return m_extra2; }
29 class PickleableNew :
public Pickleable {
31 using Pickleable::Pickleable;
34 py::class_<Pickleable>(
m,
"Pickleable")
35 .def(py::init<std::string>())
37 .def(
"extra1", &Pickleable::extra1)
38 .def(
"extra2", &Pickleable::extra2)
39 .def(
"setExtra1", &Pickleable::setExtra1)
40 .def(
"setExtra2", &Pickleable::setExtra2)
43 .def(
"__getstate__", [](
const Pickleable &
p) {
47 .def(
"__setstate__", [](Pickleable &p, py::tuple
t) {
49 throw std::runtime_error(
"Invalid state!");
51 new (&
p) Pickleable(t[0].cast<std::string>());
54 p.setExtra1(t[1].cast<int>());
55 p.setExtra2(t[2].cast<int>());
58 py::class_<PickleableNew, Pickleable>(
m,
"PickleableNew")
59 .def(py::init<std::string>())
61 [](
const PickleableNew &p) {
66 throw std::runtime_error(
"Invalid state!");
67 auto p = PickleableNew(t[0].cast<std::string>());
69 p.setExtra1(t[1].cast<int>());
70 p.setExtra2(t[2].cast<int>());
75 #if !defined(PYPY_VERSION) 77 class PickleableWithDict {
79 PickleableWithDict(
const std::string &
value) :
value(value) { }
85 class PickleableWithDictNew :
public PickleableWithDict {
87 using PickleableWithDict::PickleableWithDict;
90 py::class_<PickleableWithDict>(
m,
"PickleableWithDict", py::dynamic_attr())
91 .def(py::init<std::string>())
93 .def_readwrite(
"extra", &PickleableWithDict::extra)
94 .def(
"__getstate__", [](py::object
self) {
96 return py::make_tuple(
self.attr(
"value"),
self.attr(
"extra"),
self.attr(
"__dict__"));
98 .def(
"__setstate__", [](py::object
self, py::tuple t) {
100 throw std::runtime_error(
"Invalid state!");
102 auto& p =
self.cast<PickleableWithDict&>();
103 new (&
p) PickleableWithDict(t[0].cast<std::string>());
106 p.extra = t[1].cast<
int>();
109 self.attr(
"__dict__") = t[2];
112 py::class_<PickleableWithDictNew, PickleableWithDict>(
m,
"PickleableWithDictNew")
113 .def(py::init<std::string>())
115 [](py::object
self) {
116 return py::make_tuple(
self.attr(
"value"),
self.attr(
"extra"),
self.attr(
"__dict__"));
118 [](
const py::tuple &
t) {
120 throw std::runtime_error(
"Invalid state!");
122 auto cpp_state = PickleableWithDictNew(t[0].cast<std::string>());
123 cpp_state.extra = t[1].cast<
int>();
125 auto py_state = t[2].cast<py::dict>();
126 return std::make_pair(cpp_state, py_state);
TEST_SUBMODULE(pickling, m)
Tuple< Args... > make_tuple(Args...args)
Creates a tuple object, deducing the target type from the types of arguments.
detail::initimpl::pickle_factory< GetState, SetState > pickle(GetState &&g, SetState &&s)