From 9507a9f7957e7e42d49bbca73df092b0ed5cf844 Mon Sep 17 00:00:00 2001 From: Noah <33094578+coolreader18@users.noreply.github.com> Date: Sat, 7 Mar 2020 08:57:27 -0600 Subject: [PATCH] Add some functions from asyncio from Python 3.8 --- Lib/asyncio/events.py | 15 ++++++++++++++- Lib/asyncio/tasks.py | 23 ++++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Lib/asyncio/events.py b/Lib/asyncio/events.py index 28a45fc3c..466db6d9a 100644 --- a/Lib/asyncio/events.py +++ b/Lib/asyncio/events.py @@ -6,7 +6,8 @@ __all__ = ['AbstractEventLoopPolicy', 'get_event_loop_policy', 'set_event_loop_policy', 'get_event_loop', 'set_event_loop', 'new_event_loop', 'get_child_watcher', 'set_child_watcher', - '_set_running_loop', '_get_running_loop', + '_set_running_loop', 'get_running_loop', + '_get_running_loop', ] import functools @@ -614,6 +615,18 @@ class _RunningLoop(threading.local): _running_loop = _RunningLoop() +def get_running_loop(): + """Return the running event loop. Raise a RuntimeError if there is none. + + This function is thread-specific. + """ + # NOTE: this function is implemented in C (see _asynciomodule.c) + loop = _get_running_loop() + if loop is None: + raise RuntimeError('no running event loop') + return loop + + def _get_running_loop(): """Return the running event loop or None. diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index d31c0109f..8c4f3cca7 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -1,6 +1,6 @@ """Support for tasks, coroutines and the scheduler.""" -__all__ = ['Task', +__all__ = ['Task', 'create_task', 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED', 'wait', 'wait_for', 'as_completed', 'sleep', 'async', 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe', @@ -44,6 +44,16 @@ def _all_tasks_compat(loop=None): return {t for t in _all_tasks if futures._get_loop(t) is loop} +def _set_task_name(task, name): + if name is not None: + try: + set_name = task.set_name + except AttributeError: + pass + else: + set_name(name) + + class Task(futures.Future): """A coroutine wrapped in a Future.""" @@ -292,6 +302,17 @@ else: Task = _CTask = _asyncio.Task +def create_task(coro, *, name=None): + """Schedule the execution of a coroutine object in a spawn task. + + Return a Task object. + """ + loop = events.get_running_loop() + task = loop.create_task(coro) + _set_task_name(task, name) + return task + + # wait() and as_completed() similar to those in PEP 3148. FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED