Coroutines in Python
Introduction
Every programmer is acquainted with functions – sequences of instructions grouped together as a single unit in order to perform predetermined tasks. They admit a single entry point, are capable of accepting arguments, may or may not have a return value, and can be called at any moment during a program’s execution – including by other functions and themselves.
When a program calls a function its current execution context is saved before passing control over to the function and resuming execution. The function then creates a new context – from there on out newly created data exists exclusively during the functions runtime.
As soon as the task is complete, control is transferred back to the caller – the new context is effectively deleted and replaced by the previous one.
Coroutines
Coroutines are a special type of function that deliberately yield control over to the caller, but does not end its context in the process, instead maintaining it in an idle state.
They benefit from the ability to keep their data throughout their lifetime and, unlike functions, can have several entry points for suspending and resuming execution.
Coroutines in Python work in a very similar way to