python / python/cpython

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

Offen
#130,279 6 Kommentare 0 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@markshannon arbeitet bereits daran.

Seit 19.2.2025.

3.13 interpreter-core type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.