Fix and test weak referencing of itertools.tee objects.

This commit is contained in:
Raymond Hettinger 2004-10-17 16:40:14 +00:00
parent 837dd93e3b
commit a9f6092904
2 changed files with 14 additions and 1 deletions

View File

@ -1,6 +1,7 @@
import unittest import unittest
from test import test_support from test import test_support
from itertools import * from itertools import *
from weakref import proxy
import sys import sys
import operator import operator
import random import random
@ -382,6 +383,13 @@ class TestBasicOps(unittest.TestCase):
t3 = tnew(t1) t3 = tnew(t1)
self.assert_(list(t1) == list(t2) == list(t3) == list('abc')) self.assert_(list(t1) == list(t2) == list(t3) == list('abc'))
# test that tee objects are weak referencable
a, b = tee(xrange(10))
p = proxy(a)
self.assertEqual(getattr(p, '__class__'), type(b))
del a
self.assertRaises(ReferenceError, getattr, p, '__class__')
def test_StopIteration(self): def test_StopIteration(self):
self.assertRaises(StopIteration, izip().next) self.assertRaises(StopIteration, izip().next)

View File

@ -329,6 +329,7 @@ typedef struct {
PyObject_HEAD PyObject_HEAD
teedataobject *dataobj; teedataobject *dataobj;
int index; int index;
PyObject *weakreflist;
} teeobject; } teeobject;
static PyTypeObject teedataobject_type; static PyTypeObject teedataobject_type;
@ -452,6 +453,7 @@ tee_copy(teeobject *to)
Py_INCREF(to->dataobj); Py_INCREF(to->dataobj);
newto->dataobj = to->dataobj; newto->dataobj = to->dataobj;
newto->index = to->index; newto->index = to->index;
newto->weakreflist = NULL;
return (PyObject *)newto; return (PyObject *)newto;
} }
@ -476,6 +478,7 @@ tee_fromiterable(PyObject *iterable)
goto done; goto done;
to->dataobj = (teedataobject *)teedataobject_new(it); to->dataobj = (teedataobject *)teedataobject_new(it);
to->index = 0; to->index = 0;
to->weakreflist = NULL;
done: done:
Py_XDECREF(it); Py_XDECREF(it);
return (PyObject *)to; return (PyObject *)to;
@ -494,6 +497,8 @@ tee_new(PyTypeObject *type, PyObject *args, PyObject *kw)
static void static void
tee_dealloc(teeobject *to) tee_dealloc(teeobject *to)
{ {
if (to->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) to);
Py_XDECREF(to->dataobj); Py_XDECREF(to->dataobj);
PyObject_Del(to); PyObject_Del(to);
} }
@ -533,7 +538,7 @@ static PyTypeObject tee_type = {
0, /* tp_traverse */ 0, /* tp_traverse */
0, /* tp_clear */ 0, /* tp_clear */
0, /* tp_richcompare */ 0, /* tp_richcompare */
0, /* tp_weaklistoffset */ offsetof(teeobject, weakreflist), /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */ PyObject_SelfIter, /* tp_iter */
(iternextfunc)tee_next, /* tp_iternext */ (iternextfunc)tee_next, /* tp_iternext */
tee_methods, /* tp_methods */ tee_methods, /* tp_methods */