Skip to content

Commit 74bb0ae

Browse files
committed
simplify enum pickle implementation, added test
1 parent 7908b7a commit 74bb0ae

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

include/pybind11/pybind11.h

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1469,8 +1469,11 @@ struct enum_base {
14691469
#undef PYBIND11_ENUM_OP_CONV
14701470
#undef PYBIND11_ENUM_OP_STRICT
14711471

1472-
m_base.attr("__hash__") = cpp_function(
1472+
object getstate = cpp_function(
14731473
[](object arg) { return int_(arg); }, is_method(m_base));
1474+
1475+
m_base.attr("__getstate__") = getstate;
1476+
m_base.attr("__hash__") = getstate;
14741477
}
14751478

14761479
PYBIND11_NOINLINE void value(char const* name_, object value, const char *doc = nullptr) {
@@ -1517,10 +1520,7 @@ template <typename Type> class enum_ : public class_<Type> {
15171520
#if PY_MAJOR_VERSION < 3
15181521
def("__long__", [](Type value) { return (Scalar) value; });
15191522
#endif
1520-
1521-
// Pickling and unpickling -- needed for use with the 'multiprocessing' module
1522-
def(pickle([](const Type &value) { return pybind11::make_tuple((Scalar) value); },
1523-
[](tuple t) { return static_cast<Type>(t[0].cast<Scalar>()); }));
1523+
def("__setstate__", [](Type &value, Scalar arg) { value = static_cast<Type>(arg); });
15241524
}
15251525

15261526
/// Export enumeration entries into the parent scope

tests/test_pickling.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,9 @@ def test_roundtrip_with_dict(cls_name):
3434
assert p2.value == p.value
3535
assert p2.extra == p.extra
3636
assert p2.dynamic == p.dynamic
37+
38+
39+
def test_enum_pickle():
40+
from pybind11_tests import enums as e
41+
data = pickle.dumps(e.EOne, 2)
42+
assert e.EOne == pickle.loads(data)

0 commit comments

Comments
 (0)