how is asyncio.sleep() in python implemented?

Viewed 4522

I'm a newbie python3 enthusiast, who hopes to find out how asyncio.sleep() is implemented by the library.

I'm capable of writing coroutines but I can't seem to think about how to start writing code for asynchronous sleep.

would be great if you share the code directly or give a quick tutorial on how to find the code on my local machine. thank you!

1 Answers

For code implemented in Python (as opposed to C extensions), if you're using ipython, an easy way to see the source code is to use the ?? operator. For example, on my 3.6 install:

In [1]: import asyncio

In [2]: asyncio.sleep??
Signature: asyncio.sleep(delay, result=None, *, loop=None)
Source:
@coroutine
def sleep(delay, result=None, *, loop=None):
    """Coroutine that completes after a given time (in seconds)."""
    if delay == 0:
        yield
        return result

    if loop is None:
        loop = events.get_event_loop()
    future = loop.create_future()
    h = future._loop.call_later(delay,
                                futures._set_result_unless_cancelled,
                                future, result)
    try:
        return (yield from future)
    finally:
        h.cancel()
File:      c:\program files\python36\lib\asyncio\tasks.py
Type:      function

You can also just look at the CPython GitHub repo, but depending on the code organization it may not be obvious where to look (e.g. in this case the code actually exists in asyncio.tasks, and is auto-imported into asyncio), while ipython magic finds it for you directly.

Related