Search code examples
pythonlanguage-features

is there an alternative way of calling next on python generators?


I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the for item in generator . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?


Solution

  • Use this to wrap your generator:

    class GeneratorWrap(object):
    
          def __init__(self, generator):
              self.generator = generator
    
          def __iter__(self):
              return self
    
          def next(self):
              for o in self.generator:
                  return o
              raise StopIteration # If you don't care about the iterator protocol, remove this line and the __iter__ method.
    

    Use it like this:

    def example_generator():
        for i in [1,2,3,4,5]:
            yield i
    
    gen = GeneratorWrap(example_generator())
    print gen.next()  # prints 1
    print gen.next()  # prints 2
    

    Update: Please use the answer below because it is much better than this one.