From 4778d417336db82cf8d743efbbdb708c94fc5550 Mon Sep 17 00:00:00 2001 From: Bhuvansh Date: Sat, 1 Aug 2026 10:21:56 +0000 Subject: [PATCH] gh-154871: Fix `asyncio.Task.get_context()` crash on uninitialized tasks (GH-154898) (cherry picked from commit afd10f0e28476f5ca0eaeac34ebf85dda2cdc6e5) Co-authored-by: Bhuvansh --- Lib/test/test_asyncio/test_tasks.py | 10 ++++++++++ .../2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst | 2 ++ Modules/_asynciomodule.c | 6 +++++- 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-07-29-19-48-59.gh-issue-154871.tgZILS.rst diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py index 075fb613a21076..f6eea7fde6fac2 100644 --- a/Lib/test/test_asyncio/test_tasks.py +++ b/Lib/test/test_asyncio/test_tasks.py @@ -2967,6 +2967,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 00000000000000..8f0f1096dfe634 --- /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 ef4e4bab106301..e62f29a6b387ad 100644 --- a/Modules/_asynciomodule.c +++ b/Modules/_asynciomodule.c @@ -2814,7 +2814,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]