steve-REMOVE-THIS at cybersource.com.au
Tue Aug 10 06:12:10 CEST 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) # Same object, not a copy?
>>> 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:
"""Quick and dirty iterator."""
def __init__(self, data):
self.data = data
self.i = 0
o = self.data[self.i]
self.i += 1
>>> it = MyIter([1,2,3,4])
>>> del it.data[1:3]
More information about the Python-list