Public API

class cl.loop.Loop(*futures, loop=None, return_exceptions=False)[source]

Asyncio Event loop context manager.

Context manager which get existing event loop or if none exist will create new one.

All coroutines are converted to task and scheduled to execute in near future. Scheduling is safe for long running tasks.

Example:

Create coroutine using @asyncio.coroutine decorator or with async/await syntax

>>> async def wait_for_it(timeout):
...    await asyncio.sleep(timeout)
...    return 'success sleep for {} seconds'.format(timeout)
...

Use context manager to get result from one or more coroutines

>>> with Loop(wait_for_it(5), wait_for_it(3), return_exceptions=True) as loop:
...    result = loop.run_until_complete()
...
>>> result
['success sleep for 3 seconds', 'success sleep for 5 seconds']

When single coroutine has been scheduled to run, only single value will be returned.

>>> with Loop(wait_for_it(4)) as loop:
...    result = loop.run_until_complete()
...
>>> result
'success sleep for 4 seconds'
Parameters:
  • futures (asyncio.Future, asyncio.coroutine) – One or more coroutine or future.
  • loop (asyncio.AbstractEventLoop) – Optional existing loop.
  • return_exceptions (Boolean) – If True will return exceptions as result.
  • stop_when_done (Boolean) – If True will close the loop on context exit.
futures = None

Gathered futures.

static get_event_loop(loop: asyncio.events.AbstractEventLoop = None) → asyncio.events.AbstractEventLoop[source]

Get existing loop or create new one.

Parameters:loop (asyncio.AbstractEventLoop) – Optional, already existing loop.
Returns:Asyncio loop
Return type:asyncio.AbstractEventLoop
gather(*futures: typing.Union[asyncio.futures.Future, <function coroutine at 0x7fa43204de18>])[source]

Gather list of futures/coros and return single Task ready to schedule.

Example:

Prepare all futures to execution

>>> async def do_something():
...    return 'something'
...
>>> async def do_something_else():
...    return 'something_else'
...

Gather all tasks and then pass to context loop

>>> loop = Loop(return_exceptions=True)
>>> loop.gather(do_something(), do_something_else())
>>> with loop as l:
...    result = l.run_until_complete()
...
>>> result
['something', 'something_else']
Parameters:futures (asyncio.Future, asyncio.coroutine) – One or more coroutine or future.
Returns:Futures grouped into single future
Return type:asyncio.Task, asyncio.Future
run_until_complete()[source]

Run loop until all futures are done.

Order of result data will be the same as order of given coros.

Returns:Result, list of results or None if task has been cancelled.
Return type:None, list, Any
cancel()[source]

Cancel futures execution.

If futures are already done will return False, otherwise will return True

Returns:Cancellation status.
Return type:Boolean