python / python/cpython

`KeyboardInterrupt` not handled while evaluating a tight `while` loop condition on Python 3.13

Open
#130,279 6 comments 0 reactions 1 assignee View on GitHub

@markshannon is already working on this.

Since Feb 19, 2025.

3.13 interpreter-core type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

Consider the following infinite loop:

# test.py

class A:
    def __init__(self):
        self.shutdown_requested = False

    def start(self):
        pass

    def stop(self):
        self.shutdown_requested = True


def loop_1(a: A):
    try:
        while not a.shutdown_requested:
            pass

    except KeyboardInterrupt:
        print("in except block")

    finally:
        print("in finally block")
        a.stop()

def loop_2(a: A):
    try:
        while True:
            if a.shutdown_requested:
                break
    except KeyboardInterrupt:
        print("in except block")

    finally:
        print("in finally block")
        a.stop()


if __name__ == "__main__":
    a = A()
    a.start()
    loop_1(a)
    # loop_2(a)
^CTraceback (most recent call last):
  File "/home/harshil/test.py", line 40, in <module>
    loop_1(a)
    ~~~~~~^^^
  File "/home/harshil/test.py", line 14, in loop_1
    while not a.shutdown_requested:
              ^^^^^^^^^^^^^^^^^^^^
KeyboardInterrupt

If you run this program on Python 3.13 (3.13.1, and 3.13.2), pressing Ctrl+C does not execute the except and finally blocks in the case of loop_1(), but it works for loop_2().

If you run the same program on 3.14a5, or below 3.13, the issue does not happen, and the print statements are visible too.

CPython versions tested on:

3.12, 3.13, 3.13t, 3.14, 3.10

Operating systems tested on:

Linux

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.