Skip to content

Commit 6ed9a86

Browse files
committed
add _asdict to PyStructSequence
Signed-off-by: Filipe Laíns <[email protected]>
1 parent 668b9e5 commit 6ed9a86

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Objects/structseq.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,8 +366,35 @@ structseq_reduce(PyStructSequence* self, PyObject *Py_UNUSED(ignored))
366366
return NULL;
367367
}
368368

369+
static PyObject *
370+
structseq_asdict(PyStructSequence* self, PyObject *Py_UNUSED(ignored))
371+
{
372+
PyObject* dict = NULL;
373+
Py_ssize_t n_visible_fields, n_unnamed_fields, i;
374+
375+
n_visible_fields = VISIBLE_SIZE(self);
376+
n_unnamed_fields = UNNAMED_FIELDS(self);
377+
378+
dict = PyDict_New();
379+
if (!dict)
380+
return NULL;
381+
382+
for (i = 0; i < n_visible_fields; i++) {
383+
const char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name;
384+
if (PyDict_SetItemString(dict, n, self->ob_item[i]) < 0)
385+
goto error;
386+
}
387+
388+
return dict;
389+
390+
error:
391+
Py_XDECREF(dict);
392+
return NULL;
393+
}
394+
369395
static PyMethodDef structseq_methods[] = {
370396
{"__reduce__", (PyCFunction)structseq_reduce, METH_NOARGS, NULL},
397+
{"_asdict", (PyCFunction)structseq_asdict, METH_NOARGS, NULL},
371398
{NULL, NULL}
372399
};
373400

0 commit comments

Comments
 (0)