https://github.com/python/cpython/commit/8c2b72161e16aec7580d072865f2de4e0858a504
commit: 8c2b72161e16aec7580d072865f2de4e0858a504
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: hugovk <[email protected]>
date: 2026-08-14T17:47:02+09:00
summary:

[3.15] gh-154871: Fix `asyncio.Task.get_context()` crash on uninitialized tasks 
(GH-154898) (#155019)

gh-154871: Fix `asyncio.Task.get_context()` crash on uninitialized tasks 
(GH-154898)
(cherry picked from commit afd10f0e28476f5ca0eaeac34ebf85dda2cdc6e5)

Co-authored-by: Bhuvansh <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst
M Lib/test/test_asyncio/test_tasks.py
M Modules/_asynciomodule.c

diff --git a/Lib/test/test_asyncio/test_tasks.py 
b/Lib/test/test_asyncio/test_tasks.py
index 5e1cf518f3a38d7..48fb5139f52e5f0 100644
--- a/Lib/test/test_asyncio/test_tasks.py
+++ b/Lib/test/test_asyncio/test_tasks.py
@@ -2943,6 +2943,16 @@ async def coro():
         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
index 000000000000000..8f0f1096dfe6347
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst
@@ -0,0 +1,2 @@
+Fixed a crash in :meth:`asyncio.Task.get_context`
+when called on an uninitialized task.
diff --git a/Modules/_asynciomodule.c b/Modules/_asynciomodule.c
index f9ef789f39dc91a..a27190dadcd48c0 100644
--- a/Modules/_asynciomodule.c
+++ b/Modules/_asynciomodule.c
@@ -2795,7 +2795,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]

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to