Skip to content

Commit 6c906da

Browse files
author
Rémi Lapeyre
committed
Implement BaseException.__getnewargs_ex__
1 parent 7794862 commit 6c906da

File tree

1 file changed

+14
-42
lines changed

1 file changed

+14
-42
lines changed

Objects/exceptions.c

Lines changed: 14 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -222,54 +222,25 @@ BaseException_repr(PyBaseExceptionObject *self)
222222
static PyObject *
223223
BaseException_reduce(PyBaseExceptionObject *self, PyObject *Py_UNUSED(ignored))
224224
{
225-
PyObject *functools;
226-
PyObject *partial;
227-
PyObject *constructor;
228-
PyObject *result;
229-
PyObject **newargs;
230-
231-
_Py_IDENTIFIER(partial);
232-
functools = PyImport_ImportModule("functools");
233-
if (functools == NULL) {
234-
return NULL;
235-
}
236-
partial = _PyObject_GetAttrId(functools, &PyId_partial);
237-
Py_DECREF(functools);
238-
if (partial == NULL) {
239-
return NULL;
240-
}
241-
242-
Py_ssize_t len = 1;
243-
if (PyTuple_Check(self->args)) {
244-
len += PyTuple_GET_SIZE(self->args);
245-
}
246-
newargs = PyMem_New(PyObject *, len);
247-
if (newargs == NULL) {
248-
PyErr_NoMemory();
249-
return NULL;
225+
if (self->args && self->dict) {
226+
return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
250227
}
251-
newargs[0] = (PyObject *)Py_TYPE(self);
252-
253-
for (Py_ssize_t i=1; i < len; i++) {
254-
newargs[i] = PyTuple_GetItem(self->args, i-1);
228+
else {
229+
return PyTuple_Pack(2, Py_TYPE(self), self->args);
255230
}
256-
constructor = _PyObject_FastCallDict(partial, newargs, len, self->kwargs);
257-
PyMem_Free(newargs);
231+
}
258232

259-
Py_DECREF(partial);
233+
static PyObject *
234+
BaseException_getnewargs_ex(PyBaseExceptionObject *self, PyObject *Py_UNUSED(ignored))
235+
{
236+
PyObject *args = PyObject_GetAttrString((PyObject *) self, "args");
237+
PyObject *kwargs = PyObject_GetAttrString((PyObject *) self, "kwargs");
260238

261-
PyObject *args = PyTuple_New(0);
262-
if (args == NULL) {
239+
if (args == NULL || kwargs == NULL) {
263240
return NULL;
264241
}
265-
if (self->args && self->dict){
266-
result = PyTuple_Pack(3, constructor, args, self->dict);
267-
} else {
268-
result = PyTuple_Pack(2, constructor, args);
269-
}
270-
Py_DECREF(constructor);
271-
Py_DECREF(args);
272-
return result;
242+
243+
return Py_BuildValue("(OO)", args, kwargs);
273244
}
274245

275246
/*
@@ -312,6 +283,7 @@ PyDoc_STRVAR(with_traceback_doc,
312283

313284
static PyMethodDef BaseException_methods[] = {
314285
{"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
286+
{"__getnewargs_ex__", (PyCFunction)BaseException_getnewargs_ex, METH_NOARGS },
315287
{"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
316288
{"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
317289
with_traceback_doc},

0 commit comments

Comments
 (0)