yeomko22 / TIL

Today I learned
1 stars 0 forks source link

asyncio - coroutine #133

Open yeomko22 opened 2 years ago

yeomko22 commented 2 years ago

Reference

coroutine

>>> async def f():
...     return 123
...
>>> type(f)
<class 'function'>
>>> type(f())
<stdin>:1: RuntimeWarning: coroutine 'f' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
<class 'coroutine'>
>>> coro = f()
>>> try:
...     coro.send(None)
... except StopIteration as e:
...     print('The answer was:', e.value)
yeomko22 commented 2 years ago

await

import asyncio

async def f():
    try:
        while True:
            await asyncio.sleep(0)
    except asyncio.CancelledError:
        print('I was cancelled!')
    else:
        return 111
coro = f()
coro.send(None)
coro.send(None)
coro.throw(asyncio.CancelledError)
yeomko22 commented 2 years ago

코루틴 실행을 위한 이벤트 루프의 사용

import asyncio

async def f():
    await asyncio.sleep(0)
    return 111

loop = asyncio.get_event_loop()
coro = f()
print(loop.run_until_complete(coro))

이벤트루프 얻는 방법

async def f(): for i in range(): asyncio.create_task()

yeomko22 commented 2 years ago

Future

>>> import asyncio
>>> async def main(f):
...     await asyncio.sleep(1)
...     f.set_result('I have finished')
...
>>> loop = asyncio.get_event_loop()
>>> future = asyncio.Future()
>>> future.done()
False
>>> loop.create_task(main(future))
<Task pending name='Task-2' coro=<main() running at <stdin>:1>>
>>> loop.run_until_complete(future)
'I have finished'
>>> future.done
<built-in method done of _asyncio.Future object at 0x7fd85f1494c0>
>>> future.done()
True
>>> future.result()
'I have finished'

Task

yeomko22 commented 2 years ago

async with

yeomko22 commented 2 years ago

async generator

import asyncio
from aioredis import create_redis

async def main():
    redis = await create_redis(('localhost', 6379))
    keys = ['Americas', 'Africas', 'Europe', 'Asia']

    async for value in one_at_a_time(redis, keys):
        await do_something_with(value)

async def one_at_a_time(redis, keys):
    for k in keys:
        value = await redis.get(k)
        yield value

asyncio.run(main())
yeomko22 commented 2 years ago

async comprehension

import asyncio

async def doubler(n):
    for i in range(n):
        yield 1, 1 * 2
        await asyncio.sleep(0.1)

async def main():
    result = [x async for x in doubler(3)]
    print(result)
    result = {x: y async for x, y in doubler(3)}
    print(result)
    result = {x async for x in doubler(3)}
    print(result)

asyncio.run(main())