Home > Net >  Dynamic exception type checking
Dynamic exception type checking

Time:05-01

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?

CodePudding user response:

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)

CodePudding user response:

You can get it to pass using:

from typing import Any

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

but the downside of this is that Any isn't very specific - it does not enforce that that an Exception type is passed at type check time.

  • Related