Skip to content

Commit 1707e40

Browse files
bpo-31572: Silence only AttributeError when get the __copy__ attribute in itertools.tee(). (#3724)
1 parent d4f8480 commit 1707e40

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

Modules/itertoolsmodule.c

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -810,7 +810,7 @@ static PyObject *
810810
tee(PyObject *self, PyObject *args)
811811
{
812812
Py_ssize_t i, n=2;
813-
PyObject *it, *iterable, *copyable, *result;
813+
PyObject *it, *iterable, *copyable, *copyfunc, *result;
814814
_Py_IDENTIFIER(__copy__);
815815

816816
if (!PyArg_ParseTuple(args, "O|n", &iterable, &n))
@@ -829,25 +829,43 @@ tee(PyObject *self, PyObject *args)
829829
Py_DECREF(result);
830830
return NULL;
831831
}
832-
if (!_PyObject_HasAttrId(it, &PyId___copy__)) {
832+
833+
copyfunc = _PyObject_GetAttrId(it, &PyId___copy__);
834+
if (copyfunc != NULL) {
835+
copyable = it;
836+
}
837+
else if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
838+
Py_DECREF(it);
839+
Py_DECREF(result);
840+
return NULL;
841+
}
842+
else {
843+
PyErr_Clear();
833844
copyable = tee_fromiterable(it);
834845
Py_DECREF(it);
835846
if (copyable == NULL) {
836847
Py_DECREF(result);
837848
return NULL;
838849
}
839-
} else
840-
copyable = it;
841-
PyTuple_SET_ITEM(result, 0, copyable);
842-
for (i=1 ; i<n ; i++) {
850+
copyfunc = _PyObject_GetAttrId(copyable, &PyId___copy__);
851+
if (copyfunc == NULL) {
852+
Py_DECREF(copyable);
853+
Py_DECREF(result);
854+
return NULL;
855+
}
856+
}
843857

844-
copyable = _PyObject_CallMethodId(copyable, &PyId___copy__, NULL);
858+
PyTuple_SET_ITEM(result, 0, copyable);
859+
for (i = 1; i < n; i++) {
860+
copyable = _PyObject_CallNoArg(copyfunc);
845861
if (copyable == NULL) {
862+
Py_DECREF(copyfunc);
846863
Py_DECREF(result);
847864
return NULL;
848865
}
849866
PyTuple_SET_ITEM(result, i, copyable);
850867
}
868+
Py_DECREF(copyfunc);
851869
return result;
852870
}
853871

0 commit comments

Comments
 (0)