Skip to content

Commit 7af5cff

Browse files
committed
Support context in loop.create_task()
1 parent 7ccbe53 commit 7af5cff

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

uvloop/loop.pyx

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ include "errors.pyx"
5050

5151
cdef:
5252
int PY39 = PY_VERSION_HEX >= 0x03090000
53+
int PY311 = PY_VERSION_HEX >= 0x030b0000
5354
uint64_t MAX_SLEEP = 3600 * 24 * 365 * 100
5455

5556

@@ -1413,19 +1414,31 @@ cdef class Loop:
14131414
"""Create a Future object attached to the loop."""
14141415
return self._new_future()
14151416

1416-
def create_task(self, coro, *, name=None):
1417+
def create_task(self, coro, *, name=None, context=None):
14171418
"""Schedule a coroutine object.
14181419
14191420
Return a task object.
14201421
14211422
If name is not None, task.set_name(name) will be called if the task
14221423
object has the set_name attribute, true for default Task in Python 3.8.
1424+
1425+
An optional keyword-only context argument allows specifying a custom
1426+
contextvars.Context for the coro to run in. The current context copy is
1427+
created when no context is provided. Only available in Python 3.11.
14231428
"""
14241429
self._check_closed()
1425-
if self._task_factory is None:
1426-
task = aio_Task(coro, loop=self)
1430+
if PY311:
1431+
if self._task_factory is None:
1432+
task = aio_Task(coro, loop=self, context=context)
1433+
else:
1434+
task = self._task_factory(self, coro, context=context)
14271435
else:
1428-
task = self._task_factory(self, coro)
1436+
if UVLOOP_DEBUG:
1437+
assert context is None
1438+
if self._task_factory is None:
1439+
task = aio_Task(coro, loop=self)
1440+
else:
1441+
task = self._task_factory(self, coro)
14291442

14301443
# copied from asyncio.tasks._set_task_name (bpo-34270)
14311444
if name is not None:

0 commit comments

Comments
 (0)