2

Why is asyncio not using the builtin TimeoutError as base class?

Instead of writing

try:
    await asyncio.wait_for(asyncio.sleep(10), timeout=5)
except asyncio.TimeoutError:
    pass

one could write

try:
    await asyncio.wait_for(asyncio.sleep(10), timeout=5)
except TimeoutError:
    pass

Semnodime
  • 1,872
  • 1
  • 15
  • 24

1 Answers1

-1

I don't know why they made a separate asyncio.TimeoutError that was distinct from the plain TimeoutError in earlier versions of Python, but you may be glad to know that as of Python 3.11, the asyncio-specific asyncio.TimeoutError class has been removed, and replaced with a reference to the plain TimeoutError. That is, as of Python 3.11, asyncio.TimeoutError is TimeoutError evaluates to True, and any except TimeoutError clause will function exactly the same as any except asyncio.TimeoutError clause, and so forth. You can even test this yourself:

# THIS ONLY WORKS IN Python 3.11 AND ABOVE
import asyncio

# prints True
print(asyncio.TimeoutError is TimeoutError)

# prints "caught"
try:
    raise TimeoutError("")
except asyncio.TimeoutError:
    print("caught")

# prints "also caught"
try:
    raise asyncio.TimeoutError("")
except TimeoutError:
    print("also caught")

In Python 3.11+, we can see where asyncio.TimeoutError is defined as an alias for TimeoutError in asyncio/exceptions.py, on line 14:

"""asyncio exceptions."""


__all__ = ('BrokenBarrierError',
           'CancelledError', 'InvalidStateError', 'TimeoutError',
           'IncompleteReadError', 'LimitOverrunError',
           'SendfileNotAvailableError')


class CancelledError(BaseException):
    """The Future or Task was cancelled."""


TimeoutError = TimeoutError  # make local alias for the standard exception

# other exception definitions irrelevant to this question follow...

I don't know the Python devs' original rationale for creating an asyncio.TimeoutError exception class that is distinct from TimeoutError, but I assume they initially felt that the idea of "timing out" in async code was sufficiently different from "timing out" in regular synchronous code that there should be a new exception class for asyncio. Subsequently, they must have realized that those two versions of "timing out" aren't different enough to warrant an asyncio-specific TimeoutError, so refactored the class to be an alias instead.

Nick Muise
  • 303
  • 4
  • 10