gh-120284: Enhance asyncio.run to accept awaitable objects (#120566)

Co-authored-by: Kumar Aditya <kumaraditya@python.org>
This commit is contained in:
Ron Frederick 2024-09-25 23:15:08 -07:00 committed by GitHub
parent 46f5cbca4c
commit 1229cb8c14
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 56 additions and 22 deletions

View file

@ -3,6 +3,7 @@ __all__ = ('Runner', 'run')
import contextvars
import enum
import functools
import inspect
import threading
import signal
from . import coroutines
@ -84,10 +85,7 @@ class Runner:
return self._loop
def run(self, coro, *, context=None):
"""Run a coroutine inside the embedded event loop."""
if not coroutines.iscoroutine(coro):
raise ValueError("a coroutine was expected, got {!r}".format(coro))
"""Run code in the embedded event loop."""
if events._get_running_loop() is not None:
# fail fast with short traceback
raise RuntimeError(
@ -95,8 +93,19 @@ class Runner:
self._lazy_init()
if not coroutines.iscoroutine(coro):
if inspect.isawaitable(coro):
async def _wrap_awaitable(awaitable):
return await awaitable
coro = _wrap_awaitable(coro)
else:
raise TypeError('An asyncio.Future, a coroutine or an '
'awaitable is required')
if context is None:
context = self._context
task = self._loop.create_task(coro, context=context)
if (threading.current_thread() is threading.main_thread()