Skip to content
This repository was archived by the owner on Nov 23, 2017. It is now read-only.
This repository was archived by the owner on Nov 23, 2017. It is now read-only.

Add more highlights in docs and examples that coroutines definitions always depend on loop context #332

Open
@rudyryk

Description

@rudyryk

Hello, everyone! This is more discussion issue than bug report or kind of.

For my opinion code examples in official asyncio docs are broken. Well, not totally broken of course, but they give a wrong idea that coroutines definition are independent of loop context!

I'd stress the word definition. Because I think it's clear, that coroutines execution depends on loop. But it's totally unclear, that definition also depends on it.

Here's an example from docs:
https://docs.python.org/3/library/asyncio-task.html#example-coroutine-displaying-the-current-date

import asyncio
import datetime

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

It works.

Now let's change a single line:

loop = asyncio.new_event_loop()

It doesn't.

But the fix isn't really hard:

await asyncio.sleep(1, loop=loop)

Well, the next example is even worse:

import asyncio

async def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    await asyncio.sleep(1.0)
    return x + y

async def print_sum(x, y):
    result = await compute(x, y)
    print("%s + %s = %s" % (x, y, result))

loop = asyncio.get_event_loop()
loop.run_until_complete(print_sum(1, 2))
loop.close()

It can't run on a custom loop. Because compute() and print_sum() coroutines have no idea of event loop and thus can't be fixed without changing interface.

Well, I think we should handle that really carefully :)

Either rewrite examples in docs to provide correct patterns or handle custom loops automatically. About second option, don't know if that's possible or really good idea :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions