8

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
  • 4,781
  • 7
  • 30
  • 42
  • 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

2 Answers2

9

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
  • 124,179
  • 11
  • 158
  • 228
  • 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
0

I can't say if there's any better way, but here's how I do it.

  1. Install Pycharm (Community edition is free)

  2. Create some project and configure Python interpreter

  3. Write simple code that uses function you interested in:

.

import asyncio

asyncio.sleep()

.

  1. Ctrl+click on sleep in code

  2. Pycharm will open file with implementation of sleep function.

P.S.

I guess other modern IDE's also have similar ways to find implementations quickly.

Mikhail Gerasimov
  • 32,558
  • 15
  • 103
  • 148
  • 1
    I know it's an old thread now, but in IDLE, you can press Alt + M, then type the module name, then press enter. – Artemis Jun 24 '19 at 06:03