iter

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Tue Aug 10 00:12:10 EDT 2010


On Mon, 09 Aug 2010 09:11:37 -0700, daryn wrote:

> I'm just playing around with the iter function and I realize that I can
> use the iterator returned by it long after the original object has any
> name bound to it.

Yes, the same as everything else in Python. Iterators aren't unique here.

>>> a = [1,2,3]
>>> b = [None, a, None]
>>> id(a) == id(b[1])  # Same object, not a copy?
True
>>> del a
>>> print b
[None, [1, 2, 3], None]



> it seems as if the original object is never being garbage collected even
> though there is no name bound to it.

Of course not. That would be a Bad Thing if Python garbage collected an 
object while other objects were still using it. Can you say "core dump"?



> Does the name bound to the
> iterator object count as a reference to the original object for garbage
> collection purposes?

No, but the iterator itself does.

The technique is called *reference* counting, not "name counting". Each 
name is a reference, but not every reference is a name.


> Is there some way to retrieve/manipulate the
> original object via the iterator?

Depends on the iterator. For the standard iterator created by iter(), I 
don't think so. But for a custom iterator type, there can be if you want:

class MyIter(object):
    """Quick and dirty iterator."""
    def __init__(self, data):
        self.data = data
        self.i = 0
    def __iter__(self):
        return self
    def next(self):
        try:
            o = self.data[self.i]
        except IndexError:
            raise StopIteration
        self.i += 1
        return o


>>> it = MyIter([1,2,3,4])
>>> it.next()
1
>>> del it.data[1:3]
>>> it.next()
4




-- 
Steven



More information about the Python-list mailing list