动态异常类型检查



我试图在一些捕获异常的代码上指定类型,但异常的确切类型是动态的,即在运行时指定。

在下面运行mypy

from typing import TypeVar
ExceptionType = TypeVar('ExceptionType', bound=BaseException)
def my_func(exception_type: ExceptionType) -> None:
try:
pass
except exception_type:
pass

导致错误:

error: Exception type must be derived from BaseException

如何让它通过类型检查?

根据@jonrsharpe的注释,这是可行的:

from typing import Type, TypeVar
ExceptionType = TypeVar('ExceptionType', bound=BaseException)
def my_func(exception_type: Type[ExceptionType]) -> None:
try:
pass
except exception_type:
pass

(打字。Type自Python 3.9起已弃用,但您可能希望支持早期版本的Python)

你可以使用:

from typing import Any
def my_func(exception_type: Any) -> None:
try:
pass
except exception_type:
pass

,但这样做的缺点是Any不是非常具体-它不强制在类型检查时传递异常类型。

最新更新