13

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!

laycat
  • 5,381
  • 7
  • 31
  • 46
  • Is your goal to find the actual production code of `asyncio.sleep`, or do you want to understand how to write one yourself? The former is more involved than one would expect due to the many concerns covered by the library (e.g. cancellation, the [special-casing of `sleep(0)`](https://github.com/python/asyncio/issues/284), the option to provide a result value, etc.) – user4815162342 Aug 26 '18 at 19:37

1 Answers1

17

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • It didnt occur to me to use the call_later function which I have experimented with previously. really appreciated, thank you! – laycat Aug 26 '18 at 13:42