DEV Community

Discussion on: Explain coroutines like I'm five

Collapse
 
idanarye profile image
Idan Arye

Because Python generators don't do anything when you call the function. They only execute code when you call next (or send) on them (or when you do something that calls their next - like iterating on them with a for loop or making a list out of them)

In [1]: def single_io():
   ...:     print('starting the IO')
   ...:     yield
   ...:     print('processing the IO result')

In [2]: coroutine = single_io()

In [3]: # The coroutine did not actually start yet

In [4]: # It will only start here:

In [5]: next(coroutine)
starting the IO

In [6]:
Enter fullscreen mode Exit fullscreen mode