Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9d05c8c

Browse files
Issue #15022: Ensure all pickle protocols are supported.
1 parent dcbe46b commit 9d05c8c

2 files changed

Lines changed: 33 additions & 5 deletions

File tree

Lib/test/test_types.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1159,10 +1159,15 @@ class Spam(types.SimpleNamespace):
11591159
def test_pickle(self):
11601160
ns = types.SimpleNamespace(breakfast="spam", lunch="spam")
11611161

1162-
ns_pickled = pickle.dumps(ns)
1163-
ns_roundtrip = pickle.loads(ns_pickled)
1164-
1165-
self.assertEqual(ns, ns_roundtrip)
1162+
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1163+
pname = "protocol {}".format(protocol)
1164+
try:
1165+
ns_pickled = pickle.dumps(ns, protocol)
1166+
except TypeError as e:
1167+
raise TypeError(pname) from e
1168+
ns_roundtrip = pickle.loads(ns_pickled)
1169+
1170+
self.assertEqual(ns, ns_roundtrip, pname)
11661171

11671172

11681173
def test_main():

Objects/namespaceobject.c

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,29 @@ namespace_richcompare(PyObject *self, PyObject *other, int op)
173173
}
174174

175175

176+
PyDoc_STRVAR(namespace_reduce__doc__, "Return state information for pickling");
177+
178+
static PyObject *
179+
namespace_reduce(register _PyNamespaceObject *ns)
180+
{
181+
PyObject *result, *args = PyTuple_New(0);
182+
183+
if (!args)
184+
return NULL;
185+
186+
result = PyTuple_Pack(3, (PyObject *)Py_TYPE(ns), args, ns->ns_dict);
187+
Py_DECREF(args);
188+
return result;
189+
}
190+
191+
192+
static PyMethodDef namespace_methods[] = {
193+
{"__reduce__", (PyCFunction)namespace_reduce, METH_NOARGS,
194+
namespace_reduce__doc__},
195+
{NULL, NULL} /* sentinel */
196+
};
197+
198+
176199
PyDoc_STRVAR(namespace_doc,
177200
"A simple attribute-based namespace.\n\
178201
\n\
@@ -207,7 +230,7 @@ PyTypeObject _PyNamespace_Type = {
207230
0, /* tp_weaklistoffset */
208231
0, /* tp_iter */
209232
0, /* tp_iternext */
210-
0, /* tp_methods */
233+
namespace_methods, /* tp_methods */
211234
namespace_members, /* tp_members */
212235
0, /* tp_getset */
213236
0, /* tp_base */

0 commit comments

Comments
 (0)