pickle setstate: setattr __dict__ only if not empty (#2972)

* pickle setstate: setattr __dict__ only if not empty, to not force use of py::dynamic_attr() unnecessarily.

* Adding unit test.

* Clang 3.6 & 3.7 compatibility.

* PyPy compatibility.

* Minor iwyu fix, additional comment.

* Addressing reviewer requests.

* Applying clang-tidy suggested fixes.

* Adding check_dynamic_cast_SimpleCppDerived, related to issue #3062.
This commit is contained in:
Ralf W. Grosse-Kunstleve
2021-06-30 12:34:32 -07:00
committed by GitHub
parent 93e69191c1
commit fbae8f313b
3 changed files with 99 additions and 1 deletions

View File

@@ -1,7 +1,9 @@
// clang-format off
/*
tests/test_pickling.cpp -- pickle support
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Copyright (c) 2021 The Pybind Development Team.
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
@@ -9,6 +11,58 @@
#include "pybind11_tests.h"
// clang-format on
#include <memory>
#include <stdexcept>
#include <utility>
namespace exercise_trampoline {
struct SimpleBase {
int num = 0;
virtual ~SimpleBase() = default;
// For compatibility with old clang versions:
SimpleBase() = default;
SimpleBase(const SimpleBase &) = default;
};
struct SimpleBaseTrampoline : SimpleBase {};
struct SimpleCppDerived : SimpleBase {};
void wrap(py::module m) {
py::class_<SimpleBase, SimpleBaseTrampoline>(m, "SimpleBase")
.def(py::init<>())
.def_readwrite("num", &SimpleBase::num)
.def(py::pickle(
[](const py::object &self) {
py::dict d;
if (py::hasattr(self, "__dict__"))
d = self.attr("__dict__");
return py::make_tuple(self.attr("num"), d);
},
[](const py::tuple &t) {
if (t.size() != 2)
throw std::runtime_error("Invalid state!");
auto cpp_state = std::unique_ptr<SimpleBase>(new SimpleBaseTrampoline);
cpp_state->num = t[0].cast<int>();
auto py_state = t[1].cast<py::dict>();
return std::make_pair(std::move(cpp_state), py_state);
}));
m.def("make_SimpleCppDerivedAsBase",
[]() { return std::unique_ptr<SimpleBase>(new SimpleCppDerived); });
m.def("check_dynamic_cast_SimpleCppDerived", [](const SimpleBase *base_ptr) {
return dynamic_cast<const SimpleCppDerived *>(base_ptr) != nullptr;
});
}
} // namespace exercise_trampoline
// clang-format off
TEST_SUBMODULE(pickling, m) {
// test_roundtrip
class Pickleable {
@@ -130,4 +184,6 @@ TEST_SUBMODULE(pickling, m) {
return std::make_pair(cpp_state, py_state);
}));
#endif
exercise_trampoline::wrap(m);
}