Here is an implementation that mimics the behavior of regular generator functions:
import asyncio
class StopAsyncGenerator(Exception):
def __init__(self, value):
self.value = value
async def agen():
total = 0
for i in range(5):
total += i
yield i
raise StopAsyncGenerator(total) # Raising custom exception with value
async def main():
try:
async for value in agen():
print(value)
except StopAsyncGenerator as e:
print(f"Total sum: {e.value}")
asyncio.run(main())