mirror of
https://github.com/python/cpython.git
synced 2025-08-03 00:23:06 +00:00
gh-120284: Enhance asyncio.run
to accept awaitable objects (#120566)
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
This commit is contained in:
parent
46f5cbca4c
commit
1229cb8c14
4 changed files with 56 additions and 22 deletions
|
@ -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()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue