Skip to content

Commit 1d2d081

Browse files
committed
pythonGH-96704: Add task.get_context(), use it in call_exception_handler()
1 parent 9fbfa42 commit 1d2d081

File tree

4 files changed

+44
-2
lines changed

4 files changed

+44
-2
lines changed

Lib/asyncio/base_events.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1808,7 +1808,16 @@ def call_exception_handler(self, context):
18081808
exc_info=True)
18091809
else:
18101810
try:
1811-
self._exception_handler(self, context)
1811+
ctx = None
1812+
task = context.get("task")
1813+
if task is None:
1814+
task = context.get("future")
1815+
if task is not None and hasattr(task, "get_context"):
1816+
ctx = task.get_context()
1817+
if ctx is not None and hasattr(ctx, "run"):
1818+
ctx.run(self._exception_handler, self, context)
1819+
else:
1820+
self._exception_handler(self, context)
18121821
except (SystemExit, KeyboardInterrupt):
18131822
raise
18141823
except BaseException as exc:

Lib/asyncio/tasks.py

Lines changed: 3 additions & 0 deletions
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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2409,6 +2409,18 @@ _asyncio_Task_get_coro_impl(TaskObj *self)
24092409
return self->task_coro;
24102410
}
24112411

2412+
/*[clinic input]
2413+
_asyncio.Task.get_context
2414+
[clinic start generated code]*/
2415+
2416+
static PyObject *
2417+
_asyncio_Task_get_context_impl(TaskObj *self)
2418+
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
2419+
{
2420+
Py_INCREF(self->task_context);
2421+
return self->task_context;
2422+
}
2423+
24122424
/*[clinic input]
24132425
_asyncio.Task.get_name
24142426
[clinic start generated code]*/
@@ -2536,6 +2548,7 @@ static PyMethodDef TaskType_methods[] = {
25362548
_ASYNCIO_TASK_GET_NAME_METHODDEF
25372549
_ASYNCIO_TASK_SET_NAME_METHODDEF
25382550
_ASYNCIO_TASK_GET_CORO_METHODDEF
2551+
_ASYNCIO_TASK_GET_CONTEXT_METHODDEF
25392552
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
25402553
{NULL, NULL} /* Sentinel */
25412554
};

Modules/clinic/_asynciomodule.c.h

Lines changed: 18 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)