.. versionadded:: 3.5.2
-.. method:: loop.create_task(coro, *, name=None, context=None)
+.. method:: loop.create_task(coro, *, name=None, context=None, **kwargs)
Schedule the execution of :ref:`coroutine <coroutine>` *coro*.
Return a :class:`Task` object.
for interoperability. In this case, the result type is a subclass
of :class:`Task`.
+ The full function signature is largely the same as that of the
+ :class:`Task` constructor (or factory) - all of the keyword arguments to
+ this function are passed through to that interface, except *name*,
+ or *context* if it is ``None``.
+
If the *name* argument is provided and not ``None``, it is set as
the name of the task using :meth:`Task.set_name`.
.. versionchanged:: 3.11
Added the *context* parameter.
+ .. versionchanged:: 3.13.3
+ Added ``kwargs`` which passes on arbitrary extra parameters, including ``name`` and ``context``.
+
+ .. versionchanged:: 3.13.4
+ Rolled back the change that passes on *name* and *context* (if it is None),
+ while still passing on other arbitrary keyword arguments (to avoid breaking backwards compatibility with 3.13.3).
+
.. method:: loop.set_task_factory(factory)
Set a task factory that will be used by
event loop, and *coro* is a coroutine object. The callable
must pass on all *kwargs*, and return a :class:`asyncio.Task`-compatible object.
+ .. versionchanged:: 3.13.3
+ Required that all *kwargs* are passed on to :class:`asyncio.Task`.
+
+ .. versionchanged:: 3.13.4
+ *name* is no longer passed to task factories. *context* is no longer passed
+ to task factories if it is ``None``.
+
.. method:: loop.get_task_factory()
Return a task factory or ``None`` if the default one is in use.
"""Create a Future object attached to the loop."""
return futures.Future(loop=self)
- def create_task(self, coro, **kwargs):
+ def create_task(self, coro, *, name=None, context=None, **kwargs):
"""Schedule a coroutine object.
Return a task object.
"""
self._check_closed()
if self._task_factory is not None:
- return self._task_factory(self, coro, **kwargs)
+ if context is not None:
+ kwargs["context"] = context
+
+ task = self._task_factory(self, coro, **kwargs)
+ task.set_name(name)
+
+ else:
+ task = tasks.Task(coro, loop=self, name=name, context=context, **kwargs)
+ if task._source_traceback:
+ del task._source_traceback[-1]
- task = tasks.Task(coro, loop=self, **kwargs)
- if task._source_traceback:
- del task._source_traceback[-1]
try:
return task
finally:
# cancellation happens here and error is more understandable
await asyncio.sleep(0)
- async def test_name(self):
- name = None
-
- async def asyncfn():
- nonlocal name
- name = asyncio.current_task().get_name()
-
- async with asyncio.TaskGroup() as tg:
- tg.create_task(asyncfn(), name="example name")
-
- self.assertEqual(name, "example name")
-
class TestTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase):
loop_factory = asyncio.EventLoop