Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the class list_iterator defined?

I would like to see the definition of the class list_iterator. When I try to display its definition with the function help I get an error. Is there a module that I have to import in order to access to its help?

More precisely, I would to know how to get a reference to the object iterable that the iterator iterates. For example:

l = [1,2,3,4,5]
it = iter(l)
print(type(it))   # this prints: list_iterator
# how to get a reference to l using it

I am pretty sure the object it has a reference to the object l. This example proves it:

import sys
l = [1,2,3,4]
print(sys.getrefcount(l))   # prints 2
it = iter(l)
print(sys.getrefcount(l))   # prints 3 

So the third reference surely came from it

like image 270
ThunderPhoenix Avatar asked Nov 20 '19 21:11

ThunderPhoenix


People also ask

What is Python__ iter__?

The __iter__() function returns an iterator object that goes through each element of the given object. The next element can be accessed through __next__() function. In the case of callable object and sentinel value, the iteration is done until the value is found or the end of elements reached.

What is the use of iter in Python?

python iter() method returns the iterator object, it is used to convert an iterable to the iterator. Parameters : obj : Object which has to be converted to iterable ( usually an iterator ). sentinel : value used to represent end of sequence.


1 Answers

Does garbage collection's get_referents do it for you?

import gc

l = [1,2,3,4,5]
it = iter(l)

refs = gc.get_referents(it)  # looks like: [[1, 2, 3, 4, 5]]
assert l in refs  # True
assert l == refs[0]  # True

EDIT: It should be noted that the reference to l disappears when it is exhausted and raises StopIteration. So when you finish iterating over it, the reference-check above fails. This can be a feature or a bug depending on your use case but you should be aware of it.

# Exhaust the iterator
for x in it:
    pass

refs = gc.get_referents(it)
assert l not in refs  # No more reference to l
assert not refs  # No more reference to anything actually
like image 172
Brian Avatar answered Sep 29 '22 13:09

Brian