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 inference of local variable assigned in different branches uses type of assignment in first branch #7879

Closed
syastrov opened this issue Nov 5, 2019 · 1 comment

Comments

@syastrov
Copy link
Contributor

syastrov commented Nov 5, 2019

  • Are you reporting a bug, or opening a feature request?
    It's a matter of opinion.

  • Please insert below the code you are checking with mypy.

def foo(a: bool) -> None:
  if a:
    b = "blah"
  else:
    b = None
  return None
  • What is the actual behavior/output?
$ mypy a.py
a.py:5: error: Incompatible types in assignment (expression has type "None", variable has type "str")
  • What is the behavior/output you expect?

Since there is no annotation on b, mypy should infer that the variable b has the broadest type that matches the possible assignments: Union[str, None] (aka Optional[str]).
I didn't expect that mypy would just infer the type of the variable based on the first assignment.
FWIW: PyCharm's type inference infers the type Optional[str]

If this is not possible, then perhaps mypy could give a more meaningful error and/or hint (e.g. "error: variable b is assigned a different type based on different branches" + "hint: provide a type annotation for b: Optional[str]").

  • What are the versions of mypy and Python you are using?

Python 3.7.4 / mypy 0.750+dev.3fc382321e4531450e91c55fddb6d4ed54611d5e
(git master)

  • What are the mypy flags you are using? (For example --strict-optional)
    No flags specified, but it also occurs with --strict-optional

Related to #4061

@ilevkivskyi
Copy link
Member

Duplicate of #2611

@ilevkivskyi ilevkivskyi marked this as a duplicate of #2611 Nov 5, 2019
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