问题
Is there really no way to access the iterator object or its state from inside a for-loop?
Using pdb
or ipdb
for example, I can loop over and over again with n
, but not see in which iteration I am (ex post, I mean; of course I could use enumerate, but only before starting the debugger).
def
creates an object, and for
does the same, doesn't it? But the function has a name - and the iterator has not, is not accessible in memory? By the way, is the function accessible from within its body without knowing the name?
(The answers to questions Python: access to iterator-object in for-loops and Iterate again within the for loop suggest that it's not possible, but it seems very strange, I was used to being able to inspect anything in python.)
回答1:
What do you think the 'internal state' of an iterator should look like?
If I'm iterating over lines read from a file it would be some file buffers and a character position within the current buffer.
If I iterate over a Fibonacci sequence it's going to be the last two values used to calculate the next.
If I iterate over a database query result it might be a database cursor used to read the next row.
If I iterate over a binary tree it will be pointers to nodes in the tree.
If I iterate over a list it might just be the index of the next element.
There's no common structure to iterators in Python. It is possible that some iterators might expose part of their internal structure but that would be specific to that particular iterator. The only thing you can do with an iterator is call next()
on it to get the next element (or an Exception if there are no more).
If you want to be able to call next()
from inside the for
loop you should save a reference to the iterator, so instead of for v in someiterable: ...
you do:
iterator = iter(someiterable)
for v in iterator:
... # Can refer to `v` or even call `v.next()` here ...
This works because there is a convention in Python that constructing an iterator from an existing iterator simply gives you the existing iterator. So the for
loop won't do a separate iteration if you pass it something which is already an iterator. (Compare when you give it something which is merely iterable, each for
loop will usually iterate independently.)
来源:https://stackoverflow.com/questions/46521849/access-iterator-object-within-a-debugger