I am trying to understand coroutines in Python (and in general). I read about theory, concepts and a few examples, but I'm still struggling. I understand the asynchronous model (a few bits of Twisted), but not coroutines.
One tutorial gives this as an example of a coroutine (I made a few changes to illustrate my problem):
async def download_coroutine(url, number):
"""
A coroutine to download the specified url
"""
request = urllib.request.urlopen(url)
filename = os.path.basename(url)
print("Downloading %s" % url)
with open(filename, 'wb') as file_handle:
while True:
print(number)
chunk = request.read(1024)
if not chunk:
print("Finished")
break
file_handle.write(chunk)
msg = 'Finished downloading {filename}'.format(filename=filename)
return msg
This is done using this.
coroutines = [download_coroutine(url, number) for number, url in enumerate(urls)]
completed, pending = await asyncio.wait(coroutines)
Looking at examples of coroutines generators, I can see several operators yield. Nothing here, but urllib synchronously, AFAIK.
, , . (1, 4, 5, 1, 2,..., "",...). , , - , Finished, (3, 3, 3, 3,... "", 1, 1, 1, 1,..., ""...).
, , , .