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

前端 未结 3 1279
情话喂你
情话喂你 2020-12-02 16:06

I\'m writing a library that I\'d like end-users to be able to optionally use as if its methods and functions were not coroutines.

For example, given this function:

3条回答
  •  庸人自扰
    2020-12-02 16:33

    You need two functions -- asynchronous coroutine and synchronous regular function:

    @asyncio.coroutine
    def async_gettter():
        return (yield from 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() is actually event_loop.is_running() but I strongly don't recommend to mix sync and async code in the same function.

提交回复
热议问题