[Python-ideas] Allow creation of polymorph function (async function executable syncronously)
Nathaniel Smith
njs at pobox.com
Wed Mar 6 21:17:43 EST 2019
On Wed, Mar 6, 2019 at 4:37 PM pylang <pylang3 at gmail.com> wrote:
>> def maybe_async(fn):
>> @functools.wraps(fn)
>> def wrapper(*args, **kwargs):
>> coro = fn(*args, **kwargs)
>> if asyncio.get_running_loop() is not None:
>> return coro
>> else:
>> return await coro
>
> I was unable to run his example as-is (in Python 3.6 at least) since the `await` keyword is only permitted inside an `async def` function.
Oh yeah, that was a brain fart. I meant to write:
def maybe_async(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
coro = fn(*args, **kwargs)
if asyncio.get_running_loop() is not None:
return coro
else:
return asyncio.run(coro)
-n
--
Nathaniel J. Smith -- https://vorpus.org
More information about the Python-ideas
mailing list