Skip to content

Commit 36a7adb

Browse files
committed
pythonGH-96704: Add task.get_context(), use it in call_exception_handler()
1 parent a36235d commit 36a7adb

File tree

4 files changed

+44
-2
lines changed

4 files changed

+44
-2
lines changed

Lib/asyncio/base_events.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1794,7 +1794,16 @@ def call_exception_handler(self, context):
17941794
exc_info=True)
17951795
else:
17961796
try:
1797-
self._exception_handler(self, context)
1797+
ctx = None
1798+
task = context.get("task")
1799+
if task is None:
1800+
task = context.get("future")
1801+
if task is not None and hasattr(task, "get_context"):
1802+
ctx = task.get_context()
1803+
if ctx is not None and hasattr(ctx, "run"):
1804+
ctx.run(self._exception_handler, self, context)
1805+
else:
1806+
self._exception_handler(self, context)
17981807
except (SystemExit, KeyboardInterrupt):
17991808
raise
18001809
except BaseException as exc:

Lib/asyncio/tasks.py

+3
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,9 @@ def __repr__(self):
139139
def get_coro(self):
140140
return self._coro
141141

142+
def get_context(self):
143+
return self._context
144+
142145
def get_name(self):
143146
return self._name
144147

Modules/_asynciomodule.c

+13
Original file line numberDiff line numberDiff line change
@@ -2396,6 +2396,18 @@ _asyncio_Task_get_coro_impl(TaskObj *self)
23962396
return self->task_coro;
23972397
}
23982398

2399+
/*[clinic input]
2400+
_asyncio.Task.get_context
2401+
[clinic start generated code]*/
2402+
2403+
static PyObject *
2404+
_asyncio_Task_get_context_impl(TaskObj *self)
2405+
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
2406+
{
2407+
Py_INCREF(self->task_context);
2408+
return self->task_context;
2409+
}
2410+
23992411
/*[clinic input]
24002412
_asyncio.Task.get_name
24012413
[clinic start generated code]*/
@@ -2523,6 +2535,7 @@ static PyMethodDef TaskType_methods[] = {
25232535
_ASYNCIO_TASK_GET_NAME_METHODDEF
25242536
_ASYNCIO_TASK_SET_NAME_METHODDEF
25252537
_ASYNCIO_TASK_GET_CORO_METHODDEF
2538+
_ASYNCIO_TASK_GET_CONTEXT_METHODDEF
25262539
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
25272540
{NULL, NULL} /* Sentinel */
25282541
};

Modules/clinic/_asynciomodule.c.h

+18-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)