Reputation: 3813
Is it possible in Python - using pure a = yield
coroutine syntax, not a library like asyncio - to make a HTTP request and do something else in the meantime, before the response is received? Something like:
>>>requests.get('http://www.json-generator.com')
# do something else here while the above request is being made
Just like with AJAX one can make a request and does not have to wait for the response? Or have I possibly misunderstood the idea behind coroutines?
Upvotes: 5
Views: 1110
Reputation: 20224
You do misunderstand how coroutines work.
First, take AJAX as an example, it can work because of javascript engine. Both nodejs and javascript in browser is event-driven(Or let's say callback-driven). Which means the whole program is actually an infinite loop. And what you code is adding events to this event loop while the details of loop is hidden for you. It also hides a lot of other details for you. Such as how is response handler inserted into event loop.
Second, yield
is not really a coroutine syntax. It is a generator syntax. But as the surface structure of generator is similar with coroutine and without built-in syntax support, it can be used as coroutine syntax. While after Python3.5, we now use specific key words async
and await
for coroutine support.
Third, asyncio
works just like the engine in javascript. It provides you an event loop so that you can make a event-driven program. There are also many other lib such as eventlet
, gevent
and trio
. Basically they all do the same thing: providing event loop implementation.
Finally, you do can make your own coroutine implementation so that you don't need to rely on any lib. But that is really meaningless.
Btw, requests
itself doesn't support asynchronous operations for now(requests<3.0
).
Upvotes: 3