Skip to content

Unable to deduce/coerce types in Union #8287

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

Closed
dosisod opened this issue Jan 16, 2020 · 2 comments
Closed

Unable to deduce/coerce types in Union #8287

dosisod opened this issue Jan 16, 2020 · 2 comments

Comments

@dosisod
Copy link
Contributor

dosisod commented Jan 16, 2020

  • Are you reporting a bug, or opening a feature request?

Bug

  • Please insert below the code you are checking with mypy:
from typing import Union

def convert(num: Union[str, int]) -> int:
	if type(num) is str:
		 return int(num)

	#since we returned above, this can only be an `int`
	return num

print( convert("1") + convert(2) )
  • What is the actual behavior/output?

test.py:8: error: Incompatible return value type (got "Union[str, int]", expected "int")

  • What is the behavior/output you expect?

No error.

  • What are the versions of mypy and Python you are using?
mypy 0.761
Python 3.6.9
  • Do you see the same issue after installing mypy from Git master?

Did not check with master.

  • What are the mypy flags you are using? (For example --strict-optional)

None.

This is similar to #8264 such that the type is not deduced.

If there is N types in the Union, and one of the if statements return for a given type, there should be N-1 valid types in the Union proceeding the if statement.

This can get annoying when I have to cast the variable when I know the type:

from typing import Union, cast

def convert(num: Union[str, int]) -> int:
	if type(num) is str:
		 return int(num)

	return cast(int, num)

print( convert("1") + 2 ) # prints 3
@JukkaL
Copy link
Collaborator

JukkaL commented Jan 16, 2020

Things should work as expected if you use isinstance(num, str) instead of type(num) is str. The type(...) is check is not recommended since it doesn't work with subclasses (of str, in this case).

@JukkaL JukkaL closed this as completed Jan 16, 2020
@dosisod
Copy link
Contributor Author

dosisod commented Jan 16, 2020

This solved my problem, thanks!

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