Python Asyncio TimoutError 未使用内置 TimeoutError 作为基类

问题描述 投票:0回答:1

为什么

asyncio
不使用内置
TimeoutError
作为基类?

而不是写

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

一个人可以写

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

python-3.x python-asyncio base-class timeoutexception
1个回答
-1
投票

我不知道为什么他们制作了一个单独的

asyncio.TimeoutError
,它与早期版本的 Python 中的普通
TimeoutError
不同,但您可能会很高兴知道,从 Python 3.11 开始,特定于 asyncio 的
asyncio.TimeoutError
类已被删除,并替换为对普通
TimeoutError
的引用。也就是说,从 Python 3.11 开始,
asyncio.TimeoutError is TimeoutError
的计算结果为
True
,任何
except TimeoutError
子句的功能与任何
except asyncio.TimeoutError
子句完全相同,依此类推。您甚至可以自己测试一下:

# 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")

在 Python 3.11+ 中,我们可以看到

asyncio.TimeoutError
被定义为
TimeoutError
asyncio/exceptions.py
的别名,第 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...

我不知道 Python 开发人员创建与

asyncio.TimeoutError
不同的
TimeoutError
异常类的最初理由,但我假设他们最初认为
async
代码中的“超时”想法是完全不同的从常规同步代码中的“超时”来看,应该有一个新的 asyncio 异常类。随后,他们一定意识到这两个版本的“超时”差异不足以保证异步特定的
TimeoutError
,因此将类重构为别名。

© www.soinside.com 2019 - 2024. All rights reserved.