'python - Difference of typing with AsyncGenerator or AsyncIterator?
I make creating a discord asynchronous library that is fully typed. I have a method that create objects from a aiohttp get requests such as the following example:
async def get_bans(self):
"""|coro|
Fetches all the bans in the guild.
"""
data = await self._http.get(f"guilds/{self.id}/bans")
for ban_data in data:
yield Ban.from_dict(construct_client_dict(self._client, ban_data))
I was wondering about the return type of this code snippet and whether it should be a AsyncGenerator[Ban, None]
or AsyncIterator[Ban, None]
. To be honest i have been searching for a bit, and i could find any information that would gave me a clear idea on the subject.
Solution 1:[1]
Official documentation describes AsyncIterator as:
... that provide
__aiter__
and__anext__
methods ...
AsyncGenerator leads from documentation to PEP525.
... generator is any function containing one or more
yield
expressions ...
The result of calling an asynchronous generator function is an asynchronous generator object ...
Asynchronous generators define both of these methods (
__aiter__
and__anext__
)
So I think, because of yield
in your function it's better to use AsyncGenerator
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pyro |