mirror of
https://github.com/python/cpython.git
synced 2025-10-07 07:31:46 +00:00
bpo-46994: Accept explicit contextvars.Context in asyncio create_task() API (GH-31837)
This commit is contained in:
parent
2153daf0a0
commit
9523c0d84f
13 changed files with 209 additions and 65 deletions
|
@ -93,7 +93,7 @@ class Task(futures._PyFuture): # Inherit Python Task implementation
|
|||
# status is still pending
|
||||
_log_destroy_pending = True
|
||||
|
||||
def __init__(self, coro, *, loop=None, name=None):
|
||||
def __init__(self, coro, *, loop=None, name=None, context=None):
|
||||
super().__init__(loop=loop)
|
||||
if self._source_traceback:
|
||||
del self._source_traceback[-1]
|
||||
|
@ -112,7 +112,10 @@ class Task(futures._PyFuture): # Inherit Python Task implementation
|
|||
self._must_cancel = False
|
||||
self._fut_waiter = None
|
||||
self._coro = coro
|
||||
self._context = contextvars.copy_context()
|
||||
if context is None:
|
||||
self._context = contextvars.copy_context()
|
||||
else:
|
||||
self._context = context
|
||||
|
||||
self._loop.call_soon(self.__step, context=self._context)
|
||||
_register_task(self)
|
||||
|
@ -360,13 +363,18 @@ else:
|
|||
Task = _CTask = _asyncio.Task
|
||||
|
||||
|
||||
def create_task(coro, *, name=None):
|
||||
def create_task(coro, *, name=None, context=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)
|
||||
if context is None:
|
||||
# Use legacy API if context is not needed
|
||||
task = loop.create_task(coro)
|
||||
else:
|
||||
task = loop.create_task(coro, context=context)
|
||||
|
||||
_set_task_name(task, name)
|
||||
return task
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue