将异常类型作为参数传递,如何键入提示?

Passing an exception type as argument, how to type hint?

提问人:edd313 提问时间:11/2/2023 最后编辑:edd313 更新时间:11/9/2023 访问量:62

问:

我有一个函数,它以异常类作为参数,这是简化版本

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', got 'Type[Exception]' instead

我明白这个问题,我正在传递一个异常类而不是异常实例。 同时,我不确定如何以形式上正确且对用户具有文档价值的方式键入提示。

以下方法似乎有效,但必须有更好的方法:

def catch_exception(exception: Type[Exception]):
    ...
python 异常 类型提示

评论

5赞 Abdul Niyas P M 11/2/2023
目前的方法在我看来不错。
1赞 ChrisB 11/9/2023
Type[<Type>]确实是正确和首选的方法。这个问题涵盖了一般情况:stackoverflow.com/questions/44664040/......

答:

0赞 Robin Gugel 11/8/2023 #1

你的方式是正确和最好的方法。 如果需要异常类,则需要使用 .使用只是是错误的。Type[Exception]Exception

因此,没有比以下更好的方法了:

def catch_exception(exception: Type[Exception]):
    ...