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 is not narrowed in else clause following check via type() #18315

Closed
eroller opened this issue Dec 19, 2024 · 3 comments
Closed

Type is not narrowed in else clause following check via type() #18315

eroller opened this issue Dec 19, 2024 · 3 comments
Labels
bug mypy got something wrong

Comments

@eroller
Copy link

eroller commented Dec 19, 2024

Bug Report

Type is not narrowed in else clause following check via type()

To Reproduce

def check_type(a: int | str) -> None:
    if type(a) is int:
        my_int: int = a
    else:
        my_str: str = a # error: Incompatible types in assignment (expression has type "int | str", variable has type "str")  [assignment]

https://mypy-play.net/?mypy=latest&python=3.13&gist=20dd8e7b2f2f3a3795a78360b3627be7

Expected Behavior
Success: no issues found in 1 source file

Actual Behavior
error: Incompatible types in assignment (expression has type "int | str", variable has type "str") [assignment]

Your Environment

  • mypy 1.13.0
  • python 3.13
@eroller eroller added the bug mypy got something wrong label Dec 19, 2024
@eroller
Copy link
Author

eroller commented Dec 19, 2024

a bug (#10457) on the if clause was previously fixed

@JelleZijlstra
Copy link
Member

This behavior is correct. a might be an instance of a subtype of int.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Dec 19, 2024
@eroller
Copy link
Author

eroller commented Dec 20, 2024

Thank you. I guess that is why isinstance should be the preferred way to perform type narrowing. When I used custom classes with the @final decorator then the type is properly narrowed via type() as expected.

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

No branches or pull requests

2 participants