Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Catching CancelledError requires use of task.uncancel() #102780

Closed
Labels
@kristjanvalur

Description

@kristjanvalur

Bug report

Today I came across the following problem:

importasyncioready=asyncio.Event()asyncdeftask_func():try:ready.set()awaitasyncio.sleep(1)exceptasyncio.CancelledError:# this is required, otherwise a TimeoutError is not created below,# instead, the timeout-generated CancelledError is just raised upwards.asyncio.current_task().uncancel()finally:# Perform some cleanup, with a timeouttry:asyncwithasyncio.timeout(0):awaitasyncio.sleep(1)exceptasyncio.TimeoutError:passasyncdefmain():task=asyncio.create_task(task_func())awaitready.wait()awaitasyncio.sleep(0.01)# the task is now sleeping, lets send it an exceptiontask.cancel()# We expect the task to finish cleanly.awaittaskasyncio.run(main())

The documentation mentions that sometimes an application may want to suppressCancelledError. What it fails
to mention is that unless the cancel state is subsequently cancelled withtask.uncancel(), the task remains in a
cancelled state, and context managers such asasyncio.timeout will not work as designed. However,task.uncancel()
is not supposed to be called by user code.

I think the documentation should mention this use case fortask.uncancel(), particularly in the context of catching (and choosing to ignore)CancelledError.

This could also be considered a bug inasyncio.timeout. It prevents the use of the Timeout context manager within cleanup code, even if the intention isnot to ignore aCancelledError.

It should also be noted that the libraryasyncio_timeout on which theasyncio.timeout implementation is based, does not have this problem. Timeouts continue to work as designed, even if the task has been previously cancelled.

Your environment

  • CPython versions tested on: 3.11

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp