[issue31033] Add argument to .cancel() of Task and Future

Chris Jerdonek report at bugs.python.org
Wed May 6 07:22:08 EDT 2020


Chris Jerdonek <chris.jerdonek at gmail.com> added the comment:

I just posted a draft, proof-of-concept PR for one aspect of this issue: https://github.com/python/cpython/pull/19951

Namely, the PR makes it so that cancelled tasks have full tracebacks, all the way to where the code first gets interrupted. I did the C implementation, but I still need to do the pure Python implementation. (Note that it doesn't show where `task.cancel()` was *called*, but rather the first line of code that is cancelled. That other aspect can be handled in a separate PR.)

As an example, for this code--

    import asyncio

    async def nested():
        await asyncio.sleep(1)

    async def run():
        task = asyncio.create_task(nested())
        await asyncio.sleep(0)
        task.cancel()
        await task

    loop = asyncio.new_event_loop()
    try:
        loop.run_until_complete(run())
    finally:
        loop.close()

Python currently (before the PR) does this:

Traceback (most recent call last):
  File "/.../cpython/test-cancel.py", line 15, in <module>
    loop.run_until_complete(run())
  File "/.../cpython/Lib/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
asyncio.exceptions.CancelledError

With the PR, it looks like this. In particular, you can see that it includes "await asyncio.sleep(1)", as well as the intermediate await:

Traceback (most recent call last):
  File "/.../cpython/test-cancel.py", line 5, in nested
    await asyncio.sleep(1)
  File "/.../cpython/Lib/asyncio/tasks.py", line 657, in sleep
    return await future
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/.../cpython/test-cancel.py", line 11, in run
    await task
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/.../cpython/test-cancel.py", line 15, in <module>
    loop.run_until_complete(run())
  File "/.../cpython/Lib/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
asyncio.exceptions.CancelledError

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue31033>
_______________________________________


More information about the Python-bugs-list mailing list