When to use and when not to use Python 3.5 `await` ?

前端 未结 2 2099
渐次进展
渐次进展 2020-11-22 06:05

I\'m getting the flow of using asyncio in Python 3.5 but I haven\'t seen a description of what things I should be awaiting and things I should not

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 07:08

    You do not have much freedom. If you need to call a function you need to find out if this is a usual function or a coroutine. You must use the await keyword if and only if the function you are calling is a coroutine.

    If async functions are involved there should be an "event loop" which orchestrates these async functions. Strictly speaking it's not necessary, you can "manually" run the async method sending values to it, but probably you don't want to do it. The event loop keeps track of not-yet-finished coroutines and chooses the next one to continue running. asyncio module provides an implementation of event loop, but this is not the only possible implementation.

    Consider these two lines of code:

    x = get_x()
    do_something_else()
    

    and

    x = await aget_x()
    do_something_else()
    

    Semantic is absolutely the same: call a method which produces some value, when the value is ready assign it to variable x and do something else. In both cases the do_something_else function will be called only after the previous line of code is finished. It doesn't even mean that before or after or during the execution of asynchronous aget_x method the control will be yielded to event loop.

    Still there are some differences:

    • the second snippet can appear only inside another async function
    • aget_x function is not usual, but coroutine (that is either declared with async keyword or decorated as coroutine)
    • aget_x is able to "communicate" with the event loop: that is yield some objects to it. The event loop should be able to interpret these objects as requests to do some operations (f.e. to send a network request and wait for response, or just suspend this coroutine for n seconds). Usual get_x function is not able to communicate with event loop.

提交回复
热议问题