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

type refinement in function call #5206

Open
dfroger opened this issue Jun 12, 2018 · 5 comments

Comments

@dfroger
Copy link

@dfroger dfroger commented Jun 12, 2018

This is ok for mypy:

from typing import Union

def foo(x: Union[int, str]):
    if isinstance(x, int):
        return x + 10

but how can I make it work if the isinstance test is in a function call?

from typing import Union

def check(x: Union[int, str]) -> bool:
    return isinstance(x, int)

def foo(x: Union[int, str]):
    if check(x):
        return x + 10

I get:

foo.py:8: error: Unsupported operand types for + ("Union[int, str]" and "int")
@JelleZijlstra

This comment has been minimized.

Copy link
Collaborator

@JelleZijlstra JelleZijlstra commented Jun 12, 2018

This could perhaps be done with literal types in the future, something like this:

@overload
def check(x: int) -> Literal[True]: ...
@overload
def check(x: str) -> Literal[False]: ...
@gvanrossum

This comment has been minimized.

Copy link
Member

@gvanrossum gvanrossum commented Jun 12, 2018

@gwerbin

This comment has been minimized.

Copy link
Contributor

@gwerbin gwerbin commented Jun 12, 2018

I've had this issue recently too. I definitely think Mypy would benefit from some way to refine types by following conditional paths. Unfortunately implementing that kind of logic is well beyond my expertise.

AFAIK you would still have the problem if you wrote if True instead of if check(x), so having literal return types probably won't fix this specific problem.

@elazarg

This comment has been minimized.

Copy link
Contributor

@elazarg elazarg commented Jun 13, 2018

Related: #1203, #2357 #4063, #3062

@ilevkivskyi

This comment has been minimized.

Copy link
Collaborator

@ilevkivskyi ilevkivskyi commented Jun 13, 2018

Here I copy the relevant link from one of the above issues I just closed microsoft/TypeScript#1007

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
6 participants
You can’t perform that action at this time.