Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False exception error in raise statement with a ternary conditional operator #5128

Closed
bonotake opened this issue May 31, 2018 · 4 comments
Closed
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal topic-join-v-union Using join vs. using unions topic-ternary-expression a if b else c

Comments

@bonotake
Copy link

I faced with a strange mypy error, with such a code below:

def foo() -> None:
    message = 'test'
    raise Exception(message) if message else Exception  # -> mypy error


def bar() -> None:
    raise Exception  # ok


def baz() -> None:
    message = 'test'
    raise Exception(message)  # ok


def qux() -> None:
    message = 'test'
    raise Exception if not message else Exception(message)  # -> mypy error


if __name__ == '__main__':
    foo()

It seems legal code, but mypy produces two error messages there.

$ mypy test.py
test.py:3: error: Exception must be derived from BaseException
test.py:17: error: Exception must be derived from BaseException

Actually, this error seems to happen not only with Exception but with any other built-in exceptions.
The version of mypy is 0.600, and that of Python is 3.6.3.

Thanks in advance.

@gvanrossum gvanrossum added the bug mypy got something wrong label May 31, 2018
@gvanrossum
Copy link
Member

If you change it to

    raise Exception() if not message else Exception(message)

then it will pass.

The reason is that mypy tries to do a join on the two branches of the conditional expression and it doesn't find a common base between Exception (a type) and Exception(message) (an Exception instance), so it infers the combined type as object, which is illegal for raise.

I think we can fix this easily by evaluating the expression for raise in the context Union[Type[BaseException], BaseException].

@JelleZijlstra
Copy link
Member

This is probably related to #5095, which partially reverted #5041.

@gvanrossum
Copy link
Member

gvanrossum commented May 31, 2018 via email

@hauntsaninja
Copy link
Collaborator

Fixed in #17427

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal topic-join-v-union Using join vs. using unions topic-ternary-expression a if b else c
Projects
None yet
Development

No branches or pull requests

6 participants