Iterator & Generator

Iterator

  • For implementing iterator, it is needed to implement _iter_ and _next_ method

  • _iter_ return the class instance

  • _next_ for handling ther next iter and when to stop

class AsyncIterator():
    # constructor, define some state
    def __init__(self):
        self.counter = 0
 
    # create an instance of the iterator
    def __aiter__(self):
        return self
 
    # return the next awaitable
    async def __anext__(self):
        # check for no further items
        if self.counter >= 10:
            raise StopAsyncIteration
        # increment the counter
        self.counter += 1
        # return the counter value
        return self.counter

async def test():
    it = AsyncIterator()
    async for result in it:
	    print(result)

await test()

/** 
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
**/

Generator

  • Similar with Generator, but using yield

class AsyncIterator():
    # constructor, define some state
    def __init__(self):
        self.counter = 0
 
    # create an instance of the iterator
    def __aiter__(self):
        return self
 
    # return the next awaitable
    async def __anext__(self):
        # check for no further items
        if self.counter >= 10:
            raise StopAsyncIteration
        # increment the counter
        self.counter += 1
        # return the counter value
        return self.counter

async def test():
    it = AsyncIterator()
    async for result in it:
	    print(result)

await test()
/**
 start 
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 end
**/

Last updated

Was this helpful?