# 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

<pre class="language-python"><code class="lang-python">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()
<strong>
</strong><strong>/** 
</strong><strong> 1
</strong> 2
 3
 4
 5
 6
 7
 8
 9
 10
**/
</code></pre>

## Generator

* Similar with Generator, but using yield

```python
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
**/
```

{% embed url="https://github.com/Jwindler/Ice_story/blob/main/src/python/Asyncio/Asyncio_15.md" %}

{% embed url="https://myapollo.com.tw/blog/python-iterable-iterator-generator/" %}
