Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is asyncio.sleep() in python implemented?

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!

like image 509
laycat Avatar asked Aug 26 '18 13:08

laycat


People also ask

How does Asyncio sleep work?

The asyncio. sleep() method suspends the execution of a coroutine. Coroutines voluntarily yield CPU leading to co-operative multitasking through the await keyword.

How is Python Asyncio implemented?

asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.

How does Asyncio work in Python?

Async IO takes long waiting periods in which functions would otherwise be blocking and allows other functions to run during that downtime. (A function that blocks effectively forbids others from running from the time that it starts until the time that it returns.)

What does Asyncio sleep return?

The way this works is by using the function asyncio. sleep which is provided by the asyncio library. This function takes a single parameter which is a number of seconds, and returns a future which is not marked done yet but which will be when the specified number of seconds have passed.


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.

like image 88
ShadowRanger Avatar answered Sep 20 '22 09:09

ShadowRanger