used anywhere else; otherwise, the *iterable* could get advanced without
the tee objects being informed.
+ ``tee`` iterators are not threadsafe. A :exc:`RuntimeError` may be
+ raised when using simultaneously iterators returned by the same :func:`tee`
+ call, even if the original *iterable* is threadsafe.
+
This itertool may require significant auxiliary storage (depending on how
much temporary data needs to be stored). In general, if one iterator uses
most or all of the data before another iterator starts, it is faster to use
import copy
import pickle
from functools import reduce
+try:
+ import threading
+except ImportError:
+ threading = None
maxsize = test_support.MAX_Py_ssize_t
minsize = -maxsize-1
del forward, backward
raise
+ def test_tee_reenter(self):
+ class I:
+ first = True
+ def __iter__(self):
+ return self
+ def next(self):
+ first = self.first
+ self.first = False
+ if first:
+ return next(b)
+
+ a, b = tee(I())
+ with self.assertRaisesRegexp(RuntimeError, "tee"):
+ next(a)
+
+ @unittest.skipUnless(threading, 'Threading required for this test.')
+ def test_tee_concurrent(self):
+ start = threading.Event()
+ finish = threading.Event()
+ class I:
+ def __iter__(self):
+ return self
+ def next(self):
+ start.set()
+ finish.wait()
+
+ a, b = tee(I())
+ thread = threading.Thread(target=next, args=[a])
+ thread.start()
+ try:
+ start.wait()
+ with self.assertRaisesRegexp(RuntimeError, "tee"):
+ next(b)
+ finally:
+ finish.set()
+ thread.join()
+
def test_StopIteration(self):
self.assertRaises(StopIteration, izip().next)
--- /dev/null
+Fixed a crash in the :func:`tee` iterator when re-enter it. RuntimeError is
+now raised in this case.
PyObject_HEAD
PyObject *it;
int numread;
+ int running;
PyObject *nextlink;
PyObject *(values[LINKCELLS]);
} teedataobject;
if (tdo == NULL)
return NULL;
+ tdo->running = 0;
tdo->numread = 0;
tdo->nextlink = NULL;
Py_INCREF(it);
else {
/* this is the lead iterator, so fetch more data */
assert(i == tdo->numread);
+ if (tdo->running) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot re-enter the tee iterator");
+ return NULL;
+ }
+ tdo->running = 1;
value = PyIter_Next(tdo->it);
+ tdo->running = 0;
if (value == NULL)
return NULL;
tdo->numread++;