bpo-36999: Add asyncio.Task.get_coro() (GH-13680) · python/cpython@98ef920

6 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -842,6 +842,12 @@ Task Object

842842

The *file* argument is an I/O stream to which the output

843843

is written; by default output is written to :data:`sys.stderr`.

844844
845+

.. method:: get_coro()

846+
847+

Return the coroutine object wrapped by the :class:`Task`.

848+
849+

.. versionadded:: 3.8

850+
845851

.. method:: get_name()

846852
847853

Return the name of the Task.

Original file line numberDiff line numberDiff line change

@@ -152,6 +152,9 @@ def __del__(self):

152152

def _repr_info(self):

153153

return base_tasks._task_repr_info(self)

154154
155+

def get_coro(self):

156+

return self._coro

157+
155158

def get_name(self):

156159

return self._name

157160
Original file line numberDiff line numberDiff line change

@@ -2425,6 +2425,16 @@ async def main():

24252425
24262426

self.assertEqual(cvar.get(), -1)

24272427
2428+

def test_get_coro(self):

2429+

loop = asyncio.new_event_loop()

2430+

coro = coroutine_function()

2431+

try:

2432+

task = self.new_task(loop, coro)

2433+

loop.run_until_complete(task)

2434+

self.assertIs(task.get_coro(), coro)

2435+

finally:

2436+

loop.close()

2437+
24282438
24292439

def add_subclass_tests(cls):

24302440

BaseTask = cls.Task

Original file line numberDiff line numberDiff line change

@@ -0,0 +1,2 @@

1+

Add the ``asyncio.Task.get_coro()`` method to publicly expose the tasks's

2+

coroutine object.

Original file line numberDiff line numberDiff line change

@@ -2313,6 +2313,18 @@ _asyncio_Task_set_exception(TaskObj *self, PyObject *exception)

23132313

return NULL;

23142314

}

23152315
2316+

/*[clinic input]

2317+

_asyncio.Task.get_coro

2318+

[clinic start generated code]*/

2319+
2320+

static PyObject *

2321+

_asyncio_Task_get_coro_impl(TaskObj *self)

2322+

/*[clinic end generated code: output=bcac27c8cc6c8073 input=d2e8606c42a7b403]*/

2323+

{

2324+

Py_INCREF(self->task_coro);

2325+

return self->task_coro;

2326+

}

2327+
23162328

/*[clinic input]

23172329

_asyncio.Task.get_name

23182330

[clinic start generated code]*/

@@ -2439,6 +2451,7 @@ static PyMethodDef TaskType_methods[] = {

24392451

_ASYNCIO_TASK__REPR_INFO_METHODDEF

24402452

_ASYNCIO_TASK_GET_NAME_METHODDEF

24412453

_ASYNCIO_TASK_SET_NAME_METHODDEF

2454+

_ASYNCIO_TASK_GET_CORO_METHODDEF

24422455

{NULL, NULL} /* Sentinel */

24432456

};

24442457