How do I fix TypeError: object is not iterable with my Python tree iterator?
#1
I'm trying to understand how to properly implement a custom iterator for a tree structure in Python, but I keep getting a `TypeError` saying the object is not iterable. My `__next__` method seems correct, but I think the issue might be with how I'm resetting the traversal state each time the iteration is supposed to start fresh.
Reply
#2
That TypeError almost always means Python didn't get an actual iterator object. __next__ alone does not make something iterable. You need __iter__ that returns an iterator. If you want fresh traversal every time, have __iter__ return a new iterator object instead of returning self and reusing internal state. The clean way is to put the traversal logic in a small separate class and return that from __iter__.
Reply
#3
I tried a similar thing last month. I kept the stack on the tree object and tried to reset it in __iter__, but then a second for would fail. I ended up moving the traversal into its own iterator class that stores its own stack and takes the root when created. Then tree.__iter__ just creates that and returns it.
Reply
#4
I wonder if the real issue is that you are mutating the tree during iteration. If you reset the state in __iter__ but someone holds a reference and calls next later, you might end up with surprises. Maybe print statements helped you see when the stack gets cleared.
Reply
#5
One quick check you can do: when you run for x in tree, print the type you get from iter(tree) and inspect its attributes. If __iter__ returns self, that might be the problem. Are you sure __iter__ is being called during the for loop?
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: