2

I would like to delegate __iter__ method for an iterable container.

class DelegateIterator:
    def __init__(self, container):
        attribute = "__iter__"
        method = getattr(container, attribute)
        setattr(self, attribute, method)

d = DelegateIterator([1,2,3])
for i in d.__iter__(): # this is successful
    print(i)
for i in d: # raise error
    print(i)

The output is

1
2
3
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    for i in d:
TypeError: 'DelegateIterator' object is not iterable

Please let me know how to delegate __iter__ method.

cuzic
  • 498
  • 4
  • 6
  • `__iter__` does now work when defined as an instance variable https://stackoverflow.com/questions/43346584/why-iter-does-not-work-when-defined-as-an-instance-variable – cuzic Mar 31 '21 at 07:32

1 Answers1

5

Why overcomplicate things?

class DelegateIterator:
    def __init__(self, container):
        self.container = container

    def __iter__(self):
        return iter(self.container)
orlp
  • 112,504
  • 36
  • 218
  • 315