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

mypy confused by ternary operator #8658

Closed
dvarrazzo opened this issue Apr 11, 2020 · 1 comment
Closed

mypy confused by ternary operator #8658

dvarrazzo opened this issue Apr 11, 2020 · 1 comment

Comments

@dvarrazzo
Copy link

The two functions error_from_state_[ok|bad]() below are pretty much equivalent; one use an if statement, the other uses a conditional expression.

Mypy reports an error only in the expression case. I would expect the result to be the same.

from typing import Type, Optional

def class_for_state(state: bytes) -> Type[Exception]:
    return TypeError

def error_from_state_ok(state: Optional[bytes]) -> Exception:
    if state is not None:
        cls = class_for_state(state)
    else:
        cls = ValueError

    return cls("message")

def error_from_state_bad(state: Optional[bytes]) -> Exception:
    cls = class_for_state(state) if state is not None else ValueError
    return cls("message")

mypy --strict reports:

$ mypy --strict mypyerr.py 
mypyerr.py:16: error: Returning Any from function declared to return "Exception"

Tested with Python 3.6 and mypy 0.770 and master.

@JelleZijlstra
Copy link
Member

This is basically #4134.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants