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

generic incorrectly narrowed based on first parameter in the else branch of an if expression #11049

Open
DetachHead opened this issue Sep 3, 2021 · 1 comment
Labels
bug mypy got something wrong

Comments

@DetachHead
Copy link
Contributor

DetachHead commented Sep 3, 2021

from typing import TypeVar

T1 = TypeVar("T1")
T2 = TypeVar("T2")


def foo(a: T1, b: T2) -> T1 | T2:
    return a

invalid = 1 if 1 else foo(1, "s") # error: Argument 2 to "foo" has incompatible type "str"; expected "int"
valid = foo(1, "s") if 1 else 1

https://mypy-play.net/?mypy=latest&python=3.10&gist=791645f9a348afc114cf3769ed85c30a

@DetachHead DetachHead added the bug mypy got something wrong label Sep 3, 2021
@sobolevn
Copy link
Member

sobolevn commented Sep 17, 2021

This happens because

self.infer_function_type_arguments_using_context(
                callee, context)

infers def [T1, T2] (a: T1'3, b: T2'4) -> Union[T1'3, T2'4] to be def (a: builtins.int*, b: builtins.int*) -> builtins.int* using Literal[1] (from invalid = 1 if ...) as context. I will look into it, but it might be quite complex.

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

Successfully merging a pull request may close this issue.

2 participants