from typing import Iterable
from typing import Awaitable
from typing import List
import asyncio
import traceback


def run_all(awaitables: Iterable[Awaitable[None]]) -> List[asyncio.Task]:
    """Asynchronously runs the run_forever method of each lifetime runnable.

    Creates and runs an asyncio task for the run_forever method of each lifetime
    runnable. Calls to the run_forever method are wrapped with an error handler.

    Args:
        awaitables: An iterable of awaitable objects.

    Returns:
        List[asyncio.Task]: A list of asyncio tasks for the awaitables.
    """

    async def run_with_error_handling(awaitable: Awaitable[None]) -> None:
        try:
            await awaitable
        except Exception as e:
            # These are prints rather than logging because we just want the
            # result going directly to stdout.
            print("Task exception: {}".format(e))
            print(traceback.format_exc())

    return [
        asyncio.create_task(run_with_error_handling(awaitable))
        for awaitable in awaitables
    ]