Skip to content

Commit

Permalink
pythonGH-96704: Add task.get_context(), use it in call_exception_hand…
Browse files Browse the repository at this point in the history
…ler()
  • Loading branch information
gvanrossum committed Sep 11, 2022
1 parent a36235d commit 36a7adb
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
11 changes: 10 additions & 1 deletion Lib/asyncio/base_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -1794,7 +1794,16 @@ def call_exception_handler(self, context):
exc_info=True)
else:
try:
self._exception_handler(self, context)
ctx = None
task = context.get("task")
if task is None:
task = context.get("future")
if task is not None and hasattr(task, "get_context"):
ctx = task.get_context()
if ctx is not None and hasattr(ctx, "run"):
ctx.run(self._exception_handler, self, context)
else:
self._exception_handler(self, context)
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as exc:
Expand Down
3 changes: 3 additions & 0 deletions Lib/asyncio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@ def __repr__(self):
def get_coro(self):
return self._coro

def get_context(self):
return self._context

def get_name(self):
return self._name

Expand Down
13 changes: 13 additions & 0 deletions Modules/_asynciomodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2396,6 +2396,18 @@ _asyncio_Task_get_coro_impl(TaskObj *self)
return self->task_coro;
}

/*[clinic input]
_asyncio.Task.get_context
[clinic start generated code]*/

static PyObject *
_asyncio_Task_get_context_impl(TaskObj *self)
/*[clinic end generated code: output=6996f53d3dc01aef input=87c0b209b8fceeeb]*/
{
Py_INCREF(self->task_context);
return self->task_context;
}

/*[clinic input]
_asyncio.Task.get_name
[clinic start generated code]*/
Expand Down Expand Up @@ -2523,6 +2535,7 @@ static PyMethodDef TaskType_methods[] = {
_ASYNCIO_TASK_GET_NAME_METHODDEF
_ASYNCIO_TASK_SET_NAME_METHODDEF
_ASYNCIO_TASK_GET_CORO_METHODDEF
_ASYNCIO_TASK_GET_CONTEXT_METHODDEF
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
{NULL, NULL} /* Sentinel */
};
Expand Down
19 changes: 18 additions & 1 deletion Modules/clinic/_asynciomodule.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 36a7adb

Please sign in to comment.