Skip to content

Commit be9b776

Browse files
[3.14] gh-158126: Avoid creating AttributeError for optional Pickler attribute lookups (GH-158148) (GH-160252)
(cherry picked from commit e60a9da) Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
1 parent ffecc6a commit be9b776

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Speed up :func:`pickle.dumps` and creating a :class:`pickle.Pickler` by
2+
avoiding the creation of an :exc:`AttributeError` when looking up the
3+
optional ``reducer_override`` and ``dispatch_table`` attributes.

‎Modules/_pickle.c‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4735,6 +4735,25 @@ persistent_id(PyObject *self, PyObject *obj)
47354735
Py_RETURN_NONE;
47364736
}
47374737

4738+
static PyObject *Pickler_getattr(PyObject *self, PyObject *name);
4739+
4740+
/* Like PyObject_GetOptionalAttr(), but avoids creating an AttributeError
4741+
for a missing attribute. Must not be used for "persistent_id". */
4742+
static int
4743+
pickler_get_optional_attr(PicklerObject *self, PyObject *name,
4744+
PyObject **result)
4745+
{
4746+
if (Py_TYPE(self)->tp_getattro == Pickler_getattr) {
4747+
*result = _PyObject_GenericGetAttrWithDict((PyObject *)self, name,
4748+
NULL, 1);
4749+
if (*result != NULL) {
4750+
return 1;
4751+
}
4752+
return PyErr_Occurred() ? -1 : 0;
4753+
}
4754+
return PyObject_GetOptionalAttr((PyObject *)self, name, result);
4755+
}
4756+
47384757
static int
47394758
dump(PickleState *state, PicklerObject *self, PyObject *obj)
47404759
{
@@ -4756,8 +4775,8 @@ dump(PickleState *state, PicklerObject *self, PyObject *obj)
47564775
Py_XSETREF(self->persistent_id, tmp);
47574776

47584777
/* Cache the reducer_override method, if it exists. */
4759-
if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(reducer_override),
4760-
&tmp) < 0) {
4778+
if (pickler_get_optional_attr(self, &_Py_ID(reducer_override),
4779+
&tmp) < 0) {
47614780
goto error;
47624781
}
47634782
Py_XSETREF(self->reducer_override, tmp);
@@ -5037,8 +5056,8 @@ _pickle_Pickler___init___impl(PicklerObject *self, PyObject *file,
50375056
self->fast_memo = NULL;
50385057

50395058
if (self->dispatch_table == NULL) {
5040-
if (PyObject_GetOptionalAttr((PyObject *)self, &_Py_ID(dispatch_table),
5041-
&self->dispatch_table) < 0) {
5059+
if (pickler_get_optional_attr(self, &_Py_ID(dispatch_table),
5060+
&self->dispatch_table) < 0) {
50425061
goto error;
50435062
}
50445063
}

0 commit comments

Comments
 (0)