python iterator
in python, iterator
is any object that follows iterator protocol
. which means should include method: __iter()__
, next()
, if no next element should raise StopIteration
exception.
take an example, dict
and list
have implemented __iter()__
and __getitem__()
methods, but not implemented next()
method. so they are iterable
but not iterator
.
generator
to support delay operations, only return result when need, but not immediately return
generator funcion (with
yield
)generator expression
Python generator in other languages is called coroutines
yield
yield
is almost of return
, but it pauses every step after executing the line with yield
, and till call next()
will continue from the next line of yield
.
|
|
coroutines
example:
|
|
to run coroutine, need first call next(), then send() is called. namely, if not call next() first, send() will wait, and never be called.
the thing is, when define a python generator/coroutine, it never will run; only through await(), next() call first, which then trigger the generator/coroutine start.
asyncio
asyncronized IO, event-driven coroutine, so users can add async/await
to time-consuming IO.
- event-loop
event loop will always run, track events and enqueue them, when idle dequeue event and call event-handling() to deal with it.
- asyncio.Task
await
await only decorate async/coroutine, which is a waitable object, it works to hold the current coroutine(async func A) and wait the other coroutine(async func B) to the end.
|
|
multi-task coroutines
|
|
add coroutine sequencially
in this sample, main_thread(_loop) will sequencely run from begining to end, during running, there are two coroutines registered, when thread-safe, these two coroutines will be executed.
the whole process actually looks like run in sequencialy
|
|
add coroutines async
in this way, add/register async coroutine objects to the event-loop and execute the coroutines when thead-safe
|
|
async callback vs coroutines
compare callback and coroutines is hot topic in networking and web-js env.