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

前端 未结 4 1942
感动是毒
感动是毒 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:10

    Just return the iterator. That's what __iter__ is for. It makes no sense to try to monkey-patch the object into being in iterator and return it when you already have an iterator.

    EDIT: Now with two methods. Once, monkey patching the wrapped iterator, second, kitty-wrapping the iterator.

    class IteratorWrapperMonkey(object):
    
        def __init__(self, otheriter):
            self.otheriter = otheriter
            self.otheriter.close = self.close
    
        def close(self):
            print "Closed!"
    
        def __iter__(self):
            return self.otheriter
    
    class IteratorWrapperKitten(object):
    
        def __init__(self, otheriter):
            self.otheriter = otheriter
    
        def __iter__(self):
            return self
    
        def next(self):
            return self.otheriter.next()
    
        def close(self):
            print "Closed!"
    
    class PatchableIterator(object):
    
        def __init__(self, inp):
            self.iter = iter(inp)
    
        def next(self):
            return self.iter.next()
    
        def __iter__(self):
            return self
    
    if __name__ == "__main__":
        monkey = IteratorWrapperMonkey(PatchableIterator([1, 2, 3]))
        for i in monkey:
            print i
        monkey.close()
    
        kitten = IteratorWrapperKitten(iter([1, 2, 3]))
        for i in kitten:
            print i
        kitten.close()
    

    Both methods work both with new and old-style classes.

提交回复
热议问题