How do the async and await keywords work, exactly? Whats at the end of the await chain?

2024/10/15 23:29:37

I have this code:

async def foo(x):yield xyield x + 1async def intermediary(y):await foo(y)def bar():c = intermediary(5)

What do I put in bar to get the 5 and the 6 out of c?

I'm asking because the asyncio library seems like a lot of magic. And I want to know exactly how the magic works.

Maybe I want to write my own functions that call read or write and then inform some top level loop that I wrote that they're waiting for the file descriptor to become readable or writeable.

And then, maybe I want that top level loop to be able to resume my read and write functions (and the whole intermediate chain between the top level loop and them) once those conditions become true.

I already know how to use asyncio more or less. I wrote this little demo program that computes squares after a delay but launches lots of those tasks that each append to a list after a random interval. It's kind of clumsily written, but it works.

I want to know exactly what that program is doing under the hood. And in order to do that, I have to know how await on that sleep informs the top-level event loop that it wants to sleep (and be called again) for a bit and how the state of all the intermediate stack frames between the call to sleep and the top level event loop are frozen in place then reactivated when the delay is over.

Answer

Have you tried looking at the source for asyncio.sleep?

@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()

Basically it uses loop.call_later to set a future, and then waits for the future. Not sure this entirely answers your questions, but it might help.

https://en.xdnf.cn/q/117778.html

Related Q&A

Serial port writing style

I am using two libraries to connect with a port, and two of them uses different styles in writing these commands. I want to understand the difference because I want to use the second one, but it result…

matplotlib plot to fill figure only with data points, no borders, labels, axes,

I am after an extreme form of matplotlibs tight layout. I would like the data points to fill the figure from edge to edge without leaving any borders and without titles, axes, ticks, labels or any othe…

Chromedriver: FileNotFoundError: [WinError 2] The system cannot find the file specified Error

Have looked for an answer, but couldnt find anything. It seems insistent on saying it cant find the file specified and then checks PATH, but cant see it even then :/ Ive put the directory in PATH: http…

Python - mutable default arguments to functions

I was going through https://docs.python.org/3.5/tutorial/controlflow.html#default-argument-values. I modified the example there a little bit as below:x = [4,5] def f(a, L=x):L.append(a)return Lx = [8,9…

Python: remove duplicate items from a list while iterating

I have a list named results, I want to get rid of the duplicate items in the list, the expected result and my results does not match, I checked my code but cannot find what is the problem, what happene…

Python - SciPy Kernal Estimation Example - Density 1

Im currently working through this SciPy example on Kernal Estimation. In particular, the one labelled "Univariate estimation". As opposed to creating random data, I am using asset returns. …

PyQt QFileDialog custom proxy filter not working

This working code brings up a QFileDialog prompting the user to select a .csv file:def load(self,fileName=None):if not fileName:fileName=fileDialog.getOpenFileName(caption="Load Existing Radio Log…

If I have Pandas installed correctly, why wont my import statement recognize it?

Im working on a project to play around with a csv file, however, I cant get pandas to work. Everything I have researched so far has just told me to make sure that pandas is installed. Using pip I have …

Python Issues with a Class

I am having issues with my below class. I keep getting the below traceback, butI am not sure were I am going wrong. I am expecting to see a dictionary with photo tags. Any help would be great. Tracebac…

Dynamically populate drop down menu with selection from previous drop down menu

I have a cgi script written in Python. There are two drop down menus and then a submit button. Id like to be able to make a selection from the first menu, and based off that choice, have the second dro…