]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-128308: pass `**kwargs` to asyncio task_factory (GH-128768) (#130084)
authorAndrew Svetlov <andrew.svetlov@gmail.com>
Fri, 14 Feb 2025 16:34:17 +0000 (17:34 +0100)
committerGitHub <noreply@github.com>
Fri, 14 Feb 2025 16:34:17 +0000 (22:04 +0530)
* [3.13] gh-128308: pass `**kwargs` to asyncio task_factory (GH-128768)
(cherry picked from commit 38a99568763604ccec5d5027f0658100ad76876f)

Co-authored-by: Thomas Grainger <tagrain@gmail.com>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
---------

Co-authored-by: Thomas Grainger <tagrain@gmail.com>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
Doc/library/asyncio-eventloop.rst
Lib/asyncio/base_events.py
Lib/asyncio/events.py
Lib/test/test_asyncio/test_base_events.py
Lib/test/test_asyncio/test_eager_task_factory.py
Lib/test/test_asyncio/test_taskgroups.py
Misc/NEWS.d/next/Library/2025-01-13-07-54-32.gh-issue-128308.kYSDRF.rst [new file with mode: 0644]

index 8027d3525e59995eb8b57b7c3cd616f26ea5c366..3642a56785f3fa21ee7493f6f2e1e3015cf9e531 100644 (file)
@@ -382,9 +382,9 @@ Creating Futures and Tasks
 
    If *factory* is ``None`` the default task factory will be set.
    Otherwise, *factory* must be a *callable* with the signature matching
-   ``(loop, coro, context=None)``, where *loop* is a reference to the active
+   ``(loop, coro, **kwargs)``, where *loop* is a reference to the active
    event loop, and *coro* is a coroutine object.  The callable
-   must return a :class:`asyncio.Future`-compatible object.
+   must pass on all *kwargs*, and return a :class:`asyncio.Task`-compatible object.
 
 .. method:: loop.get_task_factory()
 
index 910fc76e884d2c5040854b199b2dbf38a000c5d4..b4a654c2dc2c66c930bbb45d1f1c37a996431112 100644 (file)
@@ -458,25 +458,18 @@ class BaseEventLoop(events.AbstractEventLoop):
         """Create a Future object attached to the loop."""
         return futures.Future(loop=self)
 
-    def create_task(self, coro, *, name=None, context=None):
+    def create_task(self, coro, **kwargs):
         """Schedule a coroutine object.
 
         Return a task object.
         """
         self._check_closed()
-        if self._task_factory is None:
-            task = tasks.Task(coro, loop=self, name=name, context=context)
-            if task._source_traceback:
-                del task._source_traceback[-1]
-        else:
-            if context is None:
-                # Use legacy API if context is not needed
-                task = self._task_factory(self, coro)
-            else:
-                task = self._task_factory(self, coro, context=context)
-
-            task.set_name(name)
+        if self._task_factory is not None:
+            return self._task_factory(self, coro, **kwargs)
 
+        task = tasks.Task(coro, loop=self, **kwargs)
+        if task._source_traceback:
+            del task._source_traceback[-1]
         try:
             return task
         finally:
@@ -490,9 +483,10 @@ class BaseEventLoop(events.AbstractEventLoop):
         If factory is None the default task factory will be set.
 
         If factory is a callable, it should have a signature matching
-        '(loop, coro)', where 'loop' will be a reference to the active
-        event loop, 'coro' will be a coroutine object.  The callable
-        must return a Future.
+        '(loop, coro, **kwargs)', where 'loop' will be a reference to the active
+        event loop, 'coro' will be a coroutine object, and **kwargs will be
+        arbitrary keyword arguments that should be passed on to Task.
+        The callable must return a Task.
         """
         if factory is not None and not callable(factory):
             raise TypeError('task factory must be a callable or None')
index be495469a0558b9c6fcfd4c55ce91efc95c00deb..3b740b9b905c0daaebc0e81eeeec29852044f3b4 100644 (file)
@@ -292,7 +292,7 @@ class AbstractEventLoop:
 
     # Method scheduling a coroutine object: create a task.
 
-    def create_task(self, coro, *, name=None, context=None):
+    def create_task(self, coro, **kwargs):
         raise NotImplementedError
 
     # Methods for interacting with threads.
index c14a0bb180d79bd39366f80794a9d68f9bf8ce77..3efb3ae9359db6c44f170917e4395b7e35ec7ef5 100644 (file)
@@ -833,8 +833,8 @@ class BaseEventLoopTests(test_utils.TestCase):
             loop.close()
 
     def test_create_named_task_with_custom_factory(self):
-        def task_factory(loop, coro):
-            return asyncio.Task(coro, loop=loop)
+        def task_factory(loop, coro, **kwargs):
+            return asyncio.Task(coro, loop=loop, **kwargs)
 
         async def test():
             pass
index 0e2b189f7615210aec89be4070aca7e4e8c545d5..179a6e44b59934190881e2a50d0ce6b08dc056bf 100644 (file)
@@ -302,6 +302,18 @@ class CEagerTaskFactoryLoopTests(EagerTaskFactoryLoopTests, test_utils.TestCase)
 
        self.run_coro(run())
 
+    def test_name(self):
+        name = None
+        async def coro():
+            nonlocal name
+            name = asyncio.current_task().get_name()
+
+        async def main():
+            task = self.loop.create_task(coro(), name="test name")
+            self.assertEqual(name, "test name")
+            await task
+
+        self.run_coro(coro())
 
 class AsyncTaskCounter:
     def __init__(self, loop, *, task_class, eager):
index ad61cb46c7c07c38296b5f7b85ffa9f1056ded9d..9f2211e3232e54a99dd6f0e9a6824800ba3458f2 100644 (file)
@@ -1081,6 +1081,18 @@ class BaseTestTaskGroup:
         # 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
diff --git a/Misc/NEWS.d/next/Library/2025-01-13-07-54-32.gh-issue-128308.kYSDRF.rst b/Misc/NEWS.d/next/Library/2025-01-13-07-54-32.gh-issue-128308.kYSDRF.rst
new file mode 100644 (file)
index 0000000..efa6138
--- /dev/null
@@ -0,0 +1 @@
+Support the *name* keyword argument for eager tasks in :func:`asyncio.loop.create_task`,  :func:`asyncio.create_task` and  :func:`asyncio.TaskGroup.create_task`, by passing on all *kwargs* to the task factory set by :func:`asyncio.loop.set_task_factory`.