what does async for do? or, how do async iterators in general work, because I'm pretty sure async for just helps you iterate on an async iterator.
I think async iterators have a method __anext__() which "steps through the iterable"? I don't understand what stepping through means.
Also __anext__() returns an awaitable? what does that mean, especially if I have something like an AsyncIterator[Object], what does the awaitable have to do with the object?
2 Comments
logging_strict@programming.dev · 2 pts · 1y
Luckily the Python community is home to giants. sqlalchemy author is one such giant and he has something of interest to contribute to this conversation. But first i bore you with stuff we all already know.
Although not a class, this pops out an AsyncIterator and shows sync equivalent.
From deep in the bowels of sqlalchemy
Should print
The decorated function can be called either as
async with fn(), orawait fn(). This is decidedly different from what@contextlib.asynccontextmanagersupports, and the usage pattern is different as well.Above,
GeneratorExitis caught if the function were used as anawait. In this case, it's essential that the cleanup does not occur, so there should not be afinallyblock.If
GeneratorExitis not invoked, this means we're in__aexit__and we were invoked as a context manager, and cleanup should proceed.So instead of a class with
__anext__and__aiter__an asyncstartablecontext withyield fromcould be a possible alternative.smq@discuss.tchncs.de · 2 pts · 1y
oh wow thanks!