Skip to content

False positive "Exception type must be derived from BaseException" #2816

@JelleZijlstra

Description

@JelleZijlstra

Mypy incorrectly emits an error when using a variable typed as a variadic tuple of exception classes in an except clause. fn1 and fn2 below trigger an error:

from typing import Tuple, Type, Union

def fn1(exc: Tuple[Type[Exception], ...]) -> None:
    try:
        1 / 0
    except exc:  # E: Exception type must be derived from BaseException
        pass

def fn2(exc: Union[Type[Exception], Tuple[Type[Exception], ...]]) -> None:
    try:
        1 / 0
    except exc:  # E: Exception type must be derived from BaseException
        pass

def fn3(exc: Type[Exception]) -> None:
    try:
        1 / 0
    except exc:  # this is fine
        pass

def fn4(exc1: Type[Exception], exc2: Type[Exception]) -> None:
    try:
        1 / 0
    except (exc1, exc2):  # this is fine too
        pass

def fn5(exc: Tuple[Type[Exception], Type[Exception]]) -> None:
    try:
        1 / 0
    except exc:  # no error
        pass

I came across this trying to add types to a function similar to @retry() from https://github.com/quora/qcore/blob/master/qcore/decorators.py#L204.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions