Python 3.9: async_generator can't be used in 'await' expression

Viewed 3003

I'm trying the following:

class Payload_Session_Generator:
    def __init__(self):
        pass
    async def __anext__(self):
        async for payload in generate_fb_payload():
            if type(payload) != str:
                yield payload
            else:
                StopAsyncIteration
    def __aiter__(self):
        return self

This is then passed as an instance to a different function and the aiter method is called explicitly and _iter is an object of the above class:

chunk = await self._iter.__anext__()

this then yields the following error:

TypeError: object async_generator can't be used in 'await' expression
1 Answers

Change your code like

class PayloadSessionGenerator:
    def __init__(self):
        pass
    
    async def __aiter__(self):
        async for payload in generate_fb_payload():
            if type(payload) != str:
                yield payload
            else:
                StopAsyncIteration

try next call

x = Payload_Session_Generator()
chunk = await x.__anext__()
Related