Skip to content

False positive statement is unreachable in try-finally related to KeyboardInterrupt #13104

Closed

Description

@bbatliner

Bug Report

A KeyboardInterrupt may interleave between the start of a try block and its contained statements. mypy seems to assume that the flow of execution will not be asynchronously interrupted.

def fn() -> None:
    i: Optional[int] = None
    try:
        i = 1
    finally:
        if i is None:
            return  # error: Statement is unreachable

Expected Behavior

It's trivial to show that this statement is reachable. Insert a sleep before the assignment:

def fn() -> None:
    i: Optional[int] = None
    try:
        time.sleep(10)
        i = 1
    finally:
        if i is None:
            print("reachable")
            return

And then Ctrl+C (KeyboardInterrupt) the function during its execution. The print will run.

Your Environment

  • Mypy version used: 0.960
  • Mypy command-line flags: --warn-unreachable seems to be the only flag necessary to reproduce this

Activity

  1. bbatliner commented on Jul 11, 2022

    @bbatliner
    Author

    Technically any exception could be raised before the statements inside of the try block execute, not just KeyboardInterrupt, via CPython's asynchronous exception state that each thread tracks: https://docs.python.org/3/c-api/init.html#c.PyThreadState_SetAsyncExc

  2. bbatliner commented on Jul 11, 2022

    @bbatliner
    Author

    What makes this extra interesting is that the unreachable block appears necessary to narrow the Optional and avoid an attribute error:

    def fn() -> None:
        s: Optional[str] = None
        try:
            s = "hello, world"
        finally:
            if s is None:
                return  # error: Statement is unreachable
            print(s.upper())
    def fn() -> None:
        s: Optional[str] = None
        try:
            s = "hello, world"
        finally:
            print(s.upper())  # Item "None" of "Optional[str]" has no attribute "upper"

    whereas such narrowing is implicit without the try-finally:

    def fn() -> None:
        s: Optional[str] = None
        s = "hello, world"
        print(s.upper())
  3. tyralla commented on Jul 20, 2025

    @tyralla
    Collaborator

    Fixed by #19270; included in Mypy 1.17.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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