Daniel Roy Greenfeld

Daniel Roy Greenfeld

About | Articles | Open Source | Books | Tags | Search

TIL: Passing exceptions as arguments in Python

Mypy needs an extra identifier to not choke on an exception passed as an argument.

Mypy needs an extra identifier to not choke on an exception passed as an argument.

This will throw a mypy error:

# code.py
class MyException(Exception):
    pass


def myfunc(custom_exception: Exception) -> None:
    try:
        print('Test')
    except custom_exception:
        print('error)

myfunc(MyException)

The error mypy will throw looks something like this:

$ mypy code.py

code.py:6: error: Exception type must be derived from BaseException (or be a tuple of exception classes)  [misc]
code.py:9: error: Argument 1 to "custom_exception" has incompatible type "type[MyException]"; expected "Exception"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

The solution is to use typing.Type:

# code.py
from typing import Type


class MyException(Exception):
    pass


def myfunc(custom_exception: Type[Exception]) -> None:
    try:
        print('Test')
    except custom_exception:
        print('error)

myfunc(MyException)
Today I Learned

Tags: TIL

← Back to all articles

Search