Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic exception type checking

I'm trying to specify types on some code that catches exceptions, but the exact type of exception is dynamic, i.e. specified at runtime.

Running mypy on the below

from typing import TypeVar

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

results in the error:

error: Exception type must be derived from BaseException

How can I get it to pass type checking?

like image 981
Michal Charemza Avatar asked Nov 17 '25 08:11

Michal Charemza


1 Answers

Based on @jonrsharpe's comments, this works:

from typing import Type, TypeVar

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

(typing.Type is deprecated since Python 3.9, but you might want to support earlier versions of Python)

like image 70
Michal Charemza Avatar answered Nov 19 '25 23:11

Michal Charemza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!