Python iterators – how to dynamically assign self.next within a new style class?

前端 未结 4 1927
感动是毒
感动是毒 2021-02-05 20:44

As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.

This works fine when I try it with an

4条回答
  •  隐瞒了意图╮
    2021-02-05 21:07

    Looks like built-in iter doesn't check for next callable in an instance but in a class and IteratorWrapper2 doesn't have any next. Below is simpler version of your problem

    class IteratorWrapper2(object):
    
        def __init__(self, otheriter):
            self.next = otheriter.next
    
        def __iter__(self):
            return self
    
    it=iter([1, 2, 3])
    myit = IteratorWrapper2(it)
    
    IteratorWrapper2.next # fails that is why iter(myit) fails
    iter(myit) # fails
    

    so the solution would be to return otheriter in __iter__

    class IteratorWrapper2(object):
    
        def __init__(self, otheriter):
            self.otheriter = otheriter
    
        def __iter__(self):
            return self.otheriter
    

    or write your own next, wrapping inner iterator

    class IteratorWrapper2(object):
    
        def __init__(self, otheriter):
            self.otheriter = otheriter
    
        def next(self):
            return self.otheriter.next()
    
        def __iter__(self):
            return self
    

    Though I do not understand why doesn't iter just use the self.next of instance.

提交回复
热议问题