Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions docs/advanced/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -893,12 +893,10 @@ An instance can now be pickled as follows:


.. note::
If given, the second argument to ``dumps`` must be 2 or larger - 0 and 1 are
not supported. Newer versions are also fine; for instance, specify ``-1`` to
always use the latest available version. Beware: failure to follow these
instructions will cause important pybind11 memory allocation routines to be
skipped during unpickling, which will likely lead to memory corruption
and/or segmentation faults.
Classes that use ``py::pickle()`` and ``py::enum_`` types support all
pickle protocols. If you bind ``__getstate__`` and ``__setstate__``
directly, the second argument to ``dumps`` must be 2 or larger; protocols
0 and 1 are not supported.

.. seealso::

Expand Down
20 changes: 17 additions & 3 deletions include/pybind11/detail/class-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,9 @@ PYBIND11_INLINE Py_ssize_t instance_data_offset() {
}
#endif

PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type) {
// `tinfo` must be `all_type_info(type)`; the caller passes it to avoid a second lookup.
PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type,
const std::vector<type_info *> &tinfo) {
#if defined(PYPY_VERSION)
// PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
// inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
Expand All @@ -725,14 +727,26 @@ PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type) {
PyObject *self = type_alloc(type);
auto *inst = get_instance(self);
// Allocate the value/holder internals:
inst->allocate_layout();
inst->allocate_layout(tinfo);

return self;
}

PYBIND11_INLINE PyObject *make_new_instance(PyTypeObject *type) {
return make_new_instance(type, all_type_info(type));
}

extern "C" PYBIND11_INLINE PyObject *
pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
return make_new_instance(type);
// Must not throw into C; reachable from pickle protocols 0 and 1 (issue #3745).
const auto &tinfo = all_type_info(type);
if (tinfo.empty()) {
std::string msg = "cannot create '" + get_fully_qualified_tp_name(type)
+ "' instances: no pybind11-registered base types";
set_error(PyExc_TypeError, msg.c_str());
return nullptr;
}
return make_new_instance(type, tinfo);
}

extern "C" PYBIND11_INLINE int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
Expand Down
1 change: 1 addition & 0 deletions include/pybind11/detail/class.h
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ Py_ssize_t static_property_dict_offset();
/// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
/// cast to a reference or pointer), and initialization is done by an `__init__` function.
PyObject *make_new_instance(PyTypeObject *type);
PyObject *make_new_instance(PyTypeObject *type, const std::vector<type_info *> &tinfo);

/// Instance creation function for all pybind11 types. It only allocates space for the
/// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
Expand Down
4 changes: 2 additions & 2 deletions include/pybind11/detail/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,8 @@ struct instance {
#endif

/// Initializes all of the above type/values/holders data (but not the instance values
/// themselves)
void allocate_layout();
/// themselves). `tinfo` must be `all_type_info()` of this instance's type.
void allocate_layout(const std::vector<type_info *> &tinfo);

/// Destroys/deallocates all of the above
void deallocate_layout();
Expand Down
6 changes: 6 additions & 0 deletions include/pybind11/detail/init.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ class type_caster<value_and_holder> {
value_and_holder *value = nullptr;
};

/// Adds a `__reduce_ex__` to `cl` that makes pickle protocols 0 and 1 work with `__setstate__`.
/// A `__reduce_ex__` that the user binds on `cl`, before or after this call, takes precedence.
void add_pickle_reduce_ex(handle cl);

PYBIND11_NAMESPACE_BEGIN(initimpl)

inline void no_nullptr(const void *ptr) {
Expand Down Expand Up @@ -523,6 +527,8 @@ struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
void execute(Class &cl, const Extra &...extra) && {
cl.def("__getstate__", std::move(get), pos_only());

add_pickle_reduce_ex(cl);

#if defined(__cpp_init_captures) && __cpp_init_captures >= 201304L
cl.def(
"__setstate__",
Expand Down
5 changes: 2 additions & 3 deletions include/pybind11/detail/type_caster_base-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,8 @@ instance::get_value_and_holder(const type_info *find_type /*= nullptr default in
#endif
}

PYBIND11_NOINLINE_ATTR PYBIND11_INLINE void instance::allocate_layout() {
const auto &tinfo = all_type_info(Py_TYPE(instance_object(this)));

PYBIND11_NOINLINE_ATTR PYBIND11_INLINE void
instance::allocate_layout(const std::vector<type_info *> &tinfo) {
const size_t n_types = tinfo.size();

if (n_types == 0) {
Expand Down
37 changes: 37 additions & 0 deletions include/pybind11/pybind11-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,43 @@ PYBIND11_INLINE void add_class_method(object &cls, const char *name_, const cpp_
}
}

PYBIND11_INLINE void add_pickle_reduce_ex(handle cl) {
if (cl.attr("__dict__").contains("__reduce_ex__")) {
return;
}
// This is a plain function without a scope, so a later user `__reduce_ex__` replaces it
// and does not join its overload chain. `cl` is not owned, which prevents a reference cycle.
cpp_function func(
[cl](const object &self, int protocol) -> object {
// Call the next `__reduce_ex__` in the MRO after `cl`.
handle object_type(reinterpret_cast<PyObject *>(&PyBaseObject_Type));
handle next = object_type;
bool after_cl = false;
for (handle base : type::handle_of(self).attr("__mro__")) {
if (after_cl && base.attr("__dict__").contains("__reduce_ex__")) {
next = base;
break;
}
after_cl = after_cl || base.is(cl);
}
// Protocols 0 and 1 do not use `__new__` and `__setstate__` by default, so reduce
// as protocol 2. The result is valid for all protocols.
if (next.is(object_type) && protocol < 2) {
protocol = 2;
}
// `super()` keeps the descriptor binding (for example a classmethod).
// PyPy on Windows does not export `PySuper_Type`.
object super_type = module_::import("builtins").attr("super");
return super_type(cl, self).attr("__reduce_ex__")(protocol);
},
name("__reduce_ex__"),
arg("self"),
arg("protocol"),
pos_only());
cl.attr("__reduce_ex__")
= reinterpret_steal<object>(PYBIND11_INSTANCE_METHOD_NEW(func.ptr(), cl.ptr()));
}

PYBIND11_INLINE str enum_name(handle arg) {
dict entries = type::handle_of(arg).attr("__entries");
for (auto kv : entries) {
Expand Down
3 changes: 3 additions & 0 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -1957,6 +1957,8 @@ Ret init(CFunc &&c, AFunc &&a) {

/// Binds pickling functions `__getstate__` and `__setstate__` and ensures that the type
/// returned by `__getstate__` is the same as the argument accepted by `__setstate__`.
/// Also binds a `__reduce_ex__` that makes protocols 0 and 1 use the protocol 2 reduction,
/// unless the class binds its own `__reduce_ex__`.
template <typename GetState, typename SetState>
detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetState &&s) {
return {std::forward<GetState>(g), std::forward<SetState>(s)};
Expand Down Expand Up @@ -2127,6 +2129,7 @@ class enum_ : public class_<Type> {
is_method(*this),
arg("state"),
pos_only());
detail::add_pickle_reduce_ex(handle(this->ptr()));
}

template <typename Func, typename... Extra>
Expand Down
67 changes: 67 additions & 0 deletions tests/test_pickling.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include <memory>
#include <stdexcept>
#include <string>
#include <utility>

namespace exercise_trampoline {
Expand Down Expand Up @@ -57,6 +58,71 @@ void wrap(py::module m) {

} // namespace exercise_trampoline

namespace user_reduce_ex {

struct Base {
std::string value;
};
struct Derived : Base {};
struct After {
std::string value;
};
struct Before {
std::string value;
};

template <typename Class>
void def_pickle(Class &cl) {
using T = typename Class::type;
cl.def(py::pickle([](const T &self) { return self.value; },
[](const std::string &value) {
T self;
self.value = value;
return self;
}));
}

template <typename Class>
void def_init_and_value(Class &cl) {
using T = typename Class::type;
cl.def(py::init([](const std::string &value) {
T self;
self.value = value;
return self;
}))
.def_readonly("value", &T::value);
}

template <typename Class>
void def_reduce_ex(Class &cl) {
cl.def("__reduce_ex__", [](const py::object &self, int protocol) {
return py::make_tuple(py::type::of(self),
py::make_tuple("custom:" + std::to_string(protocol)));
});
}

void wrap(py::module_ &m) {
// `__reduce_ex__` in a base class, `py::pickle()` in the derived class
py::class_<Base> base(m, "ReduceExBase");
def_init_and_value(base);
def_reduce_ex(base);
py::class_<Derived, Base> derived(m, "ReduceExDerived");
def_init_and_value(derived);
def_pickle(derived);

py::class_<After> after(m, "ReduceExAfter");
def_init_and_value(after);
def_pickle(after);
def_reduce_ex(after);

py::class_<Before> before(m, "ReduceExBefore");
def_init_and_value(before);
def_reduce_ex(before);
def_pickle(before);
}

} // namespace user_reduce_ex

TEST_SUBMODULE(pickling, m) {
m.def("simple_callable", []() { return 20220426; });

Expand Down Expand Up @@ -188,4 +254,5 @@ TEST_SUBMODULE(pickling, m) {
#endif

exercise_trampoline::wrap(m);
user_reduce_ex::wrap(m);
}
79 changes: 75 additions & 4 deletions tests/test_pickling.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,25 @@ def test_pickle_simple_callable(protocol):
# creates issues.


@pytest.mark.parametrize("protocol", all_pickle_protocols())
@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"])
def test_roundtrip(cls_name):
def test_roundtrip(cls_name, protocol):
cls = getattr(m, cls_name)
p = cls("test_value")
p.setExtra1(15)
p.setExtra2(48)

data = pickle.dumps(p, 2) # Must use pickle protocol >= 2
if cls_name == "Pickleable" and protocol < 2:
# Only py::pickle() supports protocols 0 and 1 (issue #3745)
if env.PYPY:
pytest.skip(
"PyPy pickles it, but loads calls __setstate__ on an uninitialized instance"
)
with pytest.raises(TypeError):
pickle.dumps(p, protocol)
return

data = pickle.dumps(p, protocol)
p2 = pickle.loads(data)
assert p2.value() == p.value()
assert p2.extra1() == p.extra1()
Expand Down Expand Up @@ -89,10 +100,63 @@ def test_roundtrip_with_dict(cls_name):
assert p2.dynamic == p.dynamic


def test_enum_pickle():
class ReduceExMixin:
def __reduce_ex__(self, protocol):
return (type(self), (f"mixin:{protocol}",))


class PyDerivedWithMixin(m.PickleableNew, ReduceExMixin):
pass


@pytest.mark.parametrize("protocol", all_pickle_protocols())
@pytest.mark.parametrize(
"cls_name", ["ReduceExDerived", "ReduceExAfter", "ReduceExBefore"]
)
def test_pickle_keeps_user_reduce_ex(cls_name, protocol):
p = getattr(m, cls_name)("x")
assert pickle.loads(pickle.dumps(p, protocol)).value == f"custom:{protocol}"


class ReduceExClassMethodMixin:
@classmethod
def __reduce_ex__(cls, protocol):
return (cls, (f"classmethod:{protocol}",))


class ReduceExStaticMethodMixin:
@staticmethod
def __reduce_ex__(protocol):
return (PyDerivedWithStaticMethod, (f"staticmethod:{protocol}",))


class PyDerivedWithClassMethod(m.PickleableNew, ReduceExClassMethodMixin):
pass


class PyDerivedWithStaticMethod(m.PickleableNew, ReduceExStaticMethodMixin):
pass


@pytest.mark.parametrize("protocol", all_pickle_protocols())
@pytest.mark.parametrize(
("cls", "kind"),
[
(PyDerivedWithMixin, "mixin"),
(PyDerivedWithClassMethod, "classmethod"),
(PyDerivedWithStaticMethod, "staticmethod"),
],
)
def test_pickle_keeps_mixin_reduce_ex(cls, kind, protocol):
p = cls("x")
assert pickle.loads(pickle.dumps(p, protocol)).value() == f"{kind}:{protocol}"


@pytest.mark.parametrize("protocol", all_pickle_protocols())
def test_enum_pickle(protocol):
from pybind11_tests import enums as e

data = pickle.dumps(e.EOne, 2)
data = pickle.dumps(e.EOne, protocol)
assert e.EOne == pickle.loads(data)


Expand Down Expand Up @@ -139,6 +203,13 @@ def test_new_style_pickle_getstate_pos_only():
)
is not None
)
assert (
re.match(
r"^__reduce_ex__\(self: object, protocol: [^,]+, /\)",
m.PickleableNew.__reduce_ex__.__doc__,
)
is not None
)
if hasattr(m, "PickleableWithDictNew"):
assert (
re.match(
Expand Down
Loading