A coroutine gets executed differently from an ordinary function (or an ordinary generator, for that matter); when you call it using the await syntax, the Python interpreter can choose to run some other code while it is waiting for your function to return a result from I/O (for example, a network request). A normal function call doesn't allow that. (A generator might, if you use yield from and do a number of other things, but you have to do them by hand, whereas the await syntax does it all for you automatically inside the interpreter.)
This is a great talk where the presenter goes into how asyncio works in detail and builds a mini version of the asyncio library:
As I understand it, async functions have an extra flag that ordinary generators don't have, and the interpreter does some different things if that flag is present. But I have not dug deeply into the source code.
def grep(pattern):
print "Looking for %s" % pattern
while True:
line = (yield)
if pattern in line:
print line,
You initialize the coroutine with g = grep("python"). Isn't this step same as having a partial function with it's `pattern` argument with value "python"? def grep(pattern, line):
if pattern in line:
print line,
And then: g = partial(grep, pattern="python")
g(line='python in a line')
I'm sure this is a very simple example of coroutines, but if this is all I want to do (setting aside async vs sync for a moment), why would I use a coroutine here instead of a partial function?EDIT: As I see more examples of coroutines especially the pipelining use cases, I was wrong and agree that it's completely different from partial functions.