Search code examples
pythonpython-asynciotyping

What is the type of asynchronous iterator?


Example (question follows):

import asyncio
import typing as t

from aiokafka import AIOKafkaConsumer


class KafkaSimpleClient:

    ...

    async def receive(self, topic: str) -> ???:
        bootstrap_servers = ','.join(
            '{}:{}'.format(host, port)
            for host, port in self._bootstrap_servers
        )
        consumer = AIOKafkaConsumer(
            loop=asyncio.get_event_loop(),
            bootstrap_servers=bootstrap_servers,
            metadata_max_age_ms=5000,
        )
        consumer.subscribe(pattern=topic)
        await consumer.start()
        return consumer

Now, I'm struggling with the return type of receive (it returns something that can be iterated over with async for x in y. What is it? Is it an awaitable iterator? Is it an iterator over awaitables? Perhaps something else entirely?

  • ??? = t.Awaitable[t.Iterator]
  • ??? = t.Iterator[t.Awaitable]
  • ??? = (Something else)

Solution

  • Source code of typing module leaves no doubts.

    async def receive(self, topic: str) -> t.AsyncIterable:
    

    or

    async def receive(self, topic: str) -> t.AsyncIterator:
    

    if you sure it'll be strictly iterator.