我有一个函数,它接受异常类作为参数,这是简化版本
def catch_exception(exception):
try:
1/0
except exception:
print("lol")
>>> catch_exception(exception=ZeroDivisionError)
lol
输入提示这应该很简单:
def catch_exception(exception: Exception):
...
但是当我使用此函数时,IDE (PyCharm) 出现问题
catch_exception(exception=ZeroDivisionError)
# Expected type 'Exception | Iterable[Exception]', got 'Type[TypeError]' instead
我理解这个问题,我传递的是异常类而不是异常实例。 同时,我不确定如何以形式正确且对用户具有文档价值的方式输入提示。
以下似乎可行,但必须有更好的方法:
def catch_exception(exception: Type[Exception]):
...
你的方法是正确且最好的方法。 如果您需要异常类,则需要使用
Type[Exception]
。仅使用 Exception
是错误的。
所以没有比以下更好的方法了:
def catch_exception(exception: Type[Exception]):
...