Skip to content

inspect.getframeinfo() doesn't handle legitimate frames with lineno=None #139531

@yilei

Description

@yilei

Bug report

Bug description:

Here is a minimal example:

import inspect
import sys

code = """
try:
    1/0
except* Exception:
    raise
"""

try:
    exec(code)
except:
    tb = sys.exc_info()[2]
    while tb:
        print(f"{tb.tb_frame=}")
        info = inspect.getframeinfo(tb.tb_frame)  # This may raise.
        tb = tb.tb_next

print("DONE")

Tested on Python 3.13.7, the output is:

tb.tb_frame=<frame at 0x7fc9bd40ac80, file '/tmp/demo.py', line 16, code <module>>
tb.tb_frame=<frame at 0x7fc9bd4ae9b0, file '<string>', line -1, code <module>>
  + Exception Group Traceback (most recent call last):
  |   File "/tmp/demo.py", line 12, in <module>
  |     exec(code)
  |     ~~~~^^^^^^
  |   File "<string>", line 4, in <module>
  | ExceptionGroup:  (1 sub-exception)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "<string>", line 3, in <module>
    | ZeroDivisionError: division by zero
    +------------------------------------

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/tmp/demo.py", line 17, in <module>
    info = inspect.getframeinfo(tb.tb_frame)  # This may raise.
  File "/root/.pyenv/versions/3.13.7/lib/python3.13/inspect.py", line 1689, in getframeinfo
    start = lineno - 1 - context//2
            ~~~~~~~^~~
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

This is reproducible in Python 3.12+. It works on Python 3.11 but it might because it doesn't have the second problematic getframeinfo call while traversing the stack:

tb.tb_frame=<frame at 0x7f41ea7f97a0, file '/tmp/demo.py', line 16, code <module>>
DONE

This might be a duplicate of #89726, but we encountered an example using exception groups and it works on Python 3.11 but not 3.12+ so I'm filing a separate bug. Feel free to dedup.

CPython versions tested on:

3.13, 3.12, 3.14

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions