Skip to content

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

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

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Sep 13, 2024
  2. picnixz commented on Sep 13, 2024

    @picnixz
    Member

    Thank you for the report but it's a known issue: #122071 and #122145. So I'm closing it as a duplicate (see also the discussion on #122161 for why we don't want (yet) fixing it like this).

  3. jpe commented on Sep 13, 2024

    @jpe
    Author

    OK, though I wish the simple fix to the traceback module had been applied. It's important that tools for reporting exceptions don't fail.

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

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions