Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python asynchronous iteration code

Practice implementing and consuming asynchronous iterators with async for, aiter(), and anext().

Intermediate ~8 min read

Challenge 1

Implement the asynchronous iterator protocol for a counter.

python Your answer
import asyncio

class Counter:
    def __init__(self, limit):
        self.current = 0
        self.limit = limit

    

async def main():
    return [value async for value in Counter(3)]

print(asyncio.run(main()))

Press Ctrl⌘Enter to check your answer

Challenge 2

Consume the asynchronous iterable with async for.

python Your answer
import asyncio

class Counter:
    def __init__(self, limit):
        self.current = 0
        self.limit = limit

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.limit:
            raise StopAsyncIteration
        value = self.current
        self.current += 1
        return value

async def main():
    values = []
    
    return values

print(asyncio.run(main()))

Press Ctrl⌘Enter to check your answer

Challenge 3

Get the asynchronous iterator explicitly and read its first value.

python Your answer
import asyncio

class Counter:
    def __init__(self, limit):
        self.current = 0
        self.limit = limit

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.limit:
            raise StopAsyncIteration
        value = self.current
        self.current += 1
        return value

async def main():
    iterator = aiter(Counter(3))
    first = 
    return first

print(asyncio.run(main()))

Press Ctrl⌘Enter to check your answer

Challenge 4

Return a fallback after the asynchronous iterator is exhausted.

python Your answer
import asyncio

class Counter:
    def __init__(self, limit):
        self.current = 0
        self.limit = limit

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.limit:
            raise StopAsyncIteration
        value = self.current
        self.current += 1
        return value

async def main():
    iterator = Counter(1)
    await anext(iterator)
    return 
print(asyncio.run(main()))

Press Ctrl⌘Enter to check your answer