]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-154871: Fix `asyncio.Task.get_context()` crash on uninitialized tasks (#154898) main
authorBhuvansh <bhuvanshkataria@gmail.com>
Sat, 1 Aug 2026 10:21:56 +0000 (10:21 +0000)
committerGitHub <noreply@github.com>
Sat, 1 Aug 2026 10:21:56 +0000 (15:51 +0530)
Lib/test/test_asyncio/test_tasks.py
Misc/NEWS.d/next/Library/2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst [new file with mode: 0644]
Modules/_asynciomodule.c

index 110cd0936c007c91b7b13db4c4ead551f3a5118a..ad9b09857f8fd2b653e9f4adeaeb3df8df32ecbb 100644 (file)
@@ -2924,6 +2924,16 @@ class CTask_CFuture_Tests(BaseTaskTests, SetMethodsTest,
         with self.assertRaises(AttributeError):
             del task._log_destroy_pending
 
+    def test_get_context_uninitialized_segfault(self):
+        # https://github.com/python/cpython/issues/154871
+
+        class UninitializedTask(self.Task):
+            def __init__(self, *args, **kwargs):
+                pass
+
+        task = UninitializedTask()
+        self.assertIsNone(task.get_context())
+
 
 @unittest.skipUnless(hasattr(futures, '_CFuture') and
                      hasattr(tasks, '_CTask'),
diff --git a/Misc/NEWS.d/next/Library/2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst b/Misc/NEWS.d/next/Library/2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst
new file mode 100644 (file)
index 0000000..8f0f109
--- /dev/null
@@ -0,0 +1,2 @@
+Fixed a crash in :meth:`asyncio.Task.get_context`
+when called on an uninitialized task.
index ec6f35f161136c11d3d4d86859170aa6ab77b372..41384b388142cccc4c317b10f47ca9c7fe74fe7b 100644 (file)
@@ -2786,7 +2786,11 @@ static PyObject *
 _asyncio_Task_get_context_impl(TaskObj *self)
 /*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
 {
-    return Py_NewRef(self->task_context);
+    if (self->task_context) {
+        return Py_NewRef(self->task_context);
+    }
+
+    Py_RETURN_NONE;
 }
 
 /*[clinic input]