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

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

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

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]):
    ...
python exception type-hinting
1个回答
0
投票

你的方法是正确且最好的方法。 如果您需要异常类,则需要使用

Type[Exception]
。仅使用
Exception
是错误的。

所以没有比以下更好的方法了:

def catch_exception(exception: Type[Exception]):
    ...
© www.soinside.com 2019 - 2024. All rights reserved.