Skip to content

Wrong unreachable note in finally section #19269

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

Open
tyralla opened this issue Jun 10, 2025 · 0 comments · May be fixed by #19270
Open

Wrong unreachable note in finally section #19269

tyralla opened this issue Jun 10, 2025 · 0 comments · May be fixed by #19270
Assignees
Labels
bug mypy got something wrong topic-reachability Detecting unreachable code

Comments

@tyralla
Copy link
Collaborator

tyralla commented Jun 10, 2025

@A5rocks found the following bug when discussing #19118:

def f4() -> None:
    while int():
        try:
            x = 1
            if int():
                x = ""
                break
            if int():
                while int():
                    if int():
                        x = None
                        break
        finally:
            if isinstance(x, str):
                print("hello :)")  # E: Statement is unreachable
            reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, None]

This bug does not need a loop and hence can be simplified to:

# Mypy 1.16.0
# --allow-redefinition-new --local-partial-types --warn-unreachable

def f() -> None:
    try:
        x = 1
        if int():
            x = ""
            return
        if int():
            x = None
            return
    finally:
        reveal_type(x)  # N: Revealed type is "Union[builtins.int, builtins.str, None]" \
                        # N: Revealed type is "builtins.int"
        if isinstance(x, str):  # E: Subclass of "int" and "str" cannot exist: would have incompatible method signatures
            reveal_type(x)  # E: Statement is unreachable \
                            # E: Revealed type is "builtins.str"
        reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str, None]" \
                       # N: Revealed type is "builtins.int"

A first idea on how to fix this.

@tyralla tyralla self-assigned this Jun 10, 2025
@tyralla tyralla added the bug mypy got something wrong label Jun 10, 2025
@A5rocks A5rocks added the topic-reachability Detecting unreachable code label Jun 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-reachability Detecting unreachable code
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants