python - How can I write asyncio coroutines that optionally act as regular functions? -


i'm writing library i'd end-users able optionally use if methods , functions not coroutines.

for example, given function:

@asyncio.coroutine def blah_getter():     return (yield http_client.get('http://blahblahblah')) 

an end user doesn't care use asynchronous features in own code, still has import asyncio , run this:

>>> response = asyncio.get_event_loop().run_until_complete(blah_getter()) 

it cool if could, inside of blah_getter determine if being called coroutine or not , react accordingly.

so like:

@asyncio.coroutine def blah_getter():     if magically_determine_if_being_yielded_from():         return (yield http_client.get('http://blahblahblah'))     else:         el = asyncio.get_event_loop()         return el.run_until_complete(http_client.get('http://blahblahblah')) 

you need 2 functions -- asynchronous coroutine , synchronous regular function:

@asyncio.coroutine def async_gettter():     return (yield http_client.get('http://example.com'))  def sync_getter()     return asyncio.get_event_loop().run_until_complete(async_getter()) 

magically_determine_if_being_yielded_from() event_loop.is_running() don't recommend mix sync , async code in same function.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -