Skip to content

3.13 traceback module print / format functions fail if incorrect source is found by linecache #124060

Closed as not planned
@jpe

Description

@jpe

Bug report

Bug description:

Functions in the traceback module such as format_exc() fail when linecache.getlines() returns a comment or other incorrect source. The following fails with an IndexError: list index out of range exception raised in the format_exc() call.

import linecache
import traceback

pseudo_filename = 'pseudo filename'
src = '1/0'
co = compile(src, filename=pseudo_filename, mode='exec')
linecache._register_code(pseudo_filename, '# a comment', pseudo_filename)
try:
    exec(co)
except Exception as exc:
    lines = traceback.format_exc()

I know linecache.._register_code() is not public and code that does something like this is buggy, but the traceback module is used to report bugs and shouldn't fail itself.

The fix is probably to check the len(tree.body) in StackSummary._should_show_carets() in traceback.py before accessing tree.body[0]

CPython versions tested on:

3.13

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions