Skip to content

Wrong unreachable note in finally section #19269

Closed

Description

@tyralla

@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.

Activity

  1. self-assigned this
    on Jun 10, 2025
  2. added a commit that references this issue on Jun 20, 2025
    4322d4f
  3. added a commit that references this issue on Jul 10, 2025
    ab4fd57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugmypy got something wrongtopic-reachabilityDetecting unreachable code

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions