How do I reset a Python tree iterator for multiple loops?
#1
I’m trying to implement a custom iterator for a tree structure in Python, and my `__next__` method is raising a `StopIteration` correctly, but it feels like the iterator state gets stuck after the first full traversal. I’m not sure if my `__iter__` method is properly resetting something, or if I’m misunderstanding how a single iterator object is supposed to work across multiple loops.
Reply
#2
I ran into this too. A single iterator object felt like it would get stuck after the first full pass. What helped was treating __iter__ as returning a fresh object for each loop, or making a clear reset method that reinitializes the internal stack and pointer when a new loop starts.
Reply
#3
Yeah, I tried to reset in __iter__ by rewinding the pointer, but then the next for loop started from the end anyway. It sometimes feels like the runtime caches the iterator somewhere and ignores Python-level resets.
Reply
#4
I keep worrying the real issue might be the traversal logic rather than the iterator protocol. If you hit a leaf and pop off the stack, you still have to unwind correctly. I added some prints to confirm which nodes get visited, and it helped me see where it stalled.
Reply
#5
One more thing I did was check what happens if someone holds onto the iterator and starts another loop later. For loops typically fetch a new iterator, but if you assigned it to a variable and reused it, you can end up with a stale state. Not sure if that matches your case, but it happened to me.
Reply


[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Forum Jump: